java里exit0,Java中C和System.exit(0)中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中,还有一些东西可以回收所有已分配的对象. (通常在操作系统级别处理.)

如果您在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担心的那种资源.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值