DestroyJavaVM 线程总是在运行

2022-01-16 00:00:00 multithreading jvm java java-threads

在分析我的应用程序时,我遇到了一个奇怪的行为 - DestroyJavaVM 线程始终在运行 - 100% 的时间.

When profiling my application I came across a weird behavior - the DestroyJavaVM thread is ALWAYS running - 100% of the time.

在对该主题进行了一些研究之后,网上几乎没有任何有价值的信息,我所理解的只是这个线程应该卸载JVM 退出时.

After doing a little research on the subject, on which there's hardly any valuable information online, all I understood is that this thread is supposed to unload the JVM upon exit.

如果是这样,为什么从我启动应用程序的第一刻起,这个线程就 100% 处于 RUNNING 状态?它不会消耗宝贵的资源,因此可能会导致 OutOfMemoryError (就像我有时会得到的那样)?

If that's the case, why is this thread in RUNNING state 100% of the time from the very first moment I start my application? Doesn't it consume valuable resources and therefore may cause an OutOfMemoryError (like I sometimes get)?

对于这个线程实际做什么以及触发它的初始化有什么官方参考?

Is there any official reference to what this thread actually does and what triggers its initialization?

谢谢

推荐答案

这是因为大多数应用程序都是在线程中运行的.

This happens because most applications are run in threads.

所有 POJO 应用程序都从调用 main 方法开始.在最简单的情况下,此方法将完成所有工作,创建对象、调用方法等.一旦 main 完成,JVM 被告知使用 DestroyJavaVM 关闭线程等待所有 非守护线程在执行之前完成工作.这是为了确保您创建的任何非守护线程在 JVM 被拆除之前运行完成.

All POJO apps start by invoking the main method. In its most simple case, this method will do all of the work, creating objects, calling methods etc. Once main completes, the JVM is told to shut down using a DestroyJavaVM thread which waits for all non-daemon threads to complete before doing its work. This is to ensure that any non-daemon threads you create run to completion before the JVM is torn down.

但是,带有 GUI 的应用程序通常作为多个线程运行.一种用于监视系统事件,例如键盘或鼠标事件.一种用于维护窗口和显示等.这种应用程序的 main 方法可能只会启动所有必需的线程并退出.它仍然会创建 DestroyJavaVM 线程,但现在它所做的只是等待您创建的所有线程完成,然后再拆除 VM.

An app with a GUI, however, normally runs as a number of threads. One for watching for system events such as keyboard or mouse events. One for maintaining the windows and display etc. The main method of this kind of app will probably just start up all the required threads and exit. It still creates the DestroyJavaVM thread but now all that it does is wait for all of your created threads to finish before tearing down the VM.

因此,任何创建线程并仅依赖其功能的应用程序将始终有一个 DestroyJavaVM 线程等待它完成.由于它所做的只是join所有其他正在运行的线程,它不会消耗任何资源.

As a result, any app that creates threads and relies solely on their functionality will always have a DestroyJavaVM thread waiting for it to finish. Since all it is doing is joining all other running threads it does not consume any resources.

相关文章