But to use System.exit(0) in java – how is it here? Could one trust the garbage-collector in this context?
在Java中调用System.exit时,垃圾回收器通常不会运行1.但是,在我听说过的任何JVM中,还有一些东西可以回收所有已分配的对象. (通常在操作系统级别处理.)
如果您在JVM终止之前依赖于对象终结器,那么GC不运行的事实才有意义.
假设,如果您的Java应用程序使用JNI(等)来调用本机方法,那么这些方法可以访问可能存在问题的系统资源.然而:
>作为一般规则,操作系统会处理这些事情.至少它适用于现代版本的Linux和UNIX,AFAIK.
>垃圾收集器无论如何都不了解这些资源.如果操作系统无法回收它们,那么Java垃圾收集器将无济于事.
如果确实需要清理Java程序获取的这些资源(通过本机代码),那么最好的方法是在本机代码方法中实现清理,并使用“shutdown hook”来运行它们.如果调用System.exit,将运行关闭挂钩.
1 – 如果您之前调用了runFinalizersOnExit(true),则将在JVM出口上执行垃圾收集.但是,这是一种弃用的方法. Oracle网站解释如下:
Q: Why is Runtime.runFinalizersOnExit deprecated?
A: Because it is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock. While this problem could be prevented if the class whose objects are being finalized were coded to “defend against” this call, most programmers do not defend against it. They assume that an object is dead at the time that its finalizer is called.
Further, the call is not “thread-safe” in the sense that it sets a VM-global flag. This forces every class with a finalizer to defend against the finalization of live objects!
简而言之,这是一种危险的方法,它不会直接处理OP担心的那种资源.