问题
I plan to use an object which is called by my main method to exit the entire program. The object has a method which just runs a System.exit(0).
My question is, is this a safe thing to do? If I run System.exit(0)
from another object, will garbage collection still clean out the entire program from memory, or will I have issues cleaning the calling class from memory? My thoughts are that either since the JVM will be terminated, the calling class will be garbage-collected, or that I might have issues cleaning the calling class from memory since the object's stack frame is above the main stack frame. It's mainly an issue of me not yet knowing enough about Java... Thanks for any help!
回答1:
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)
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/33532774/will-calling-system-exit0-from-an-object-outside-of-main-run-garbage-collecti