Search code examples
javagarbage-collectionexitexit-codegarbage

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


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!


Solution

  • 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)