java - C中exit(0)和Java中System.exit(0)的实践

标签 java android c garbage-collection exit

如果有替代方案,在 C 中使用 exit(0) 不是一个好习惯,因为它不会释放资源。但是要在 Java 中使用 System.exit(0) - 这里是怎么回事?在这种情况下,可以信任垃圾收集器吗?

C语言:

 exit(0);

Java:

 System.exit(0)

最佳答案

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 中,还有其他东西可以回收所有已分配的对象。 (通常它是在操作系统级别处理的。)

GC 不运行这一事实仅在您依赖对象终结器来处理 JVM 终止之前的重要事情时才有意义。

假设,如果您的 Java 应用程序使用 JNI(等)调用 native 方法,那么这些方法可能会访问可能有问题的系统资源。然而:

  1. 作为一般规则,操作系统处理这些事情。至少它适用于现代版本的 Linux 和 UNIX,AFAIK。

  2. 垃圾收集器无论如何都不知道这些资源。如果操作系统无法回收它们,那么 Java 垃圾收集器将无济于事。

如果您确实需要清理 Java 程序获取的此类资源(通过 native 代码),那么最好的方法是在 native 代码方法中实现清理,并使用“关闭 Hook ”来运行它们。如果您调用 System.exit,关闭 Hook 将运行。


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 担心的那种资源。

关于java - C中exit(0)和Java中System.exit(0)的实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20181860/

相关文章:

Java:监听列表中的值是否发生变化

java - Observable.zip 问题

java - 从 RAM 运行 Java 应用程序

java - org.apache.http.ProtocolException : Target host is not specified

android - 如何使用工具:locale for strings. xml文件?

java - 将任务依赖项添加到 Gradle 中的现有插件任务?

java - 无法使 PreferenceFragment 工作(编译错误)

c - 如何同时接受字符串输入?

c - 如何从文件中读取大量的float?

c - 为什么下面的 C 代码不起作用?我无法找出错误。