Will calling System.exit(0); from an object outside of main run garbage collection?

半世苍凉 提交于 2019-12-02 04:32:29
Wesley

System.exit() is a static function therefore it doesn't matter where you call it. The effects are the same which is terminating the Java Virtual Machine. Any resources used by the JVM upon termination are given back to the OS.

Source: http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit(int)

System.exit(any int) will terminate the application. The memory both native and heap would be freed up to the operating system.

This would terminate the "java" process. On linux, do

ps -eaf | grep java

to view the process after System.exit call and you would see that it has exited and there is no trace of it. This implies that this process is not running and any resources: memory, cpu assigned to it are claimed by the OS.

On the GC front, a clarification, the GC is also an integral part of any java application (process) and would also terminate with it. System.exit would not provide for GC to run or any cleanup to take place.

If you would like a cleanup, allow for a shutdown hook and System.exit() in this case would invoke the shutdown hook allowing for cleanup such as shutting down threads etc.

Using System.exit(0) will flush the whole application from the stack and heap. Use VisualVM while running your program to confirm this. I can't get to it, but I have an application that ramps up to a few GBs worth of memory utilization. I've put a System.exit() statement in one of the objects and saw all the memory be freed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!