What is the exact purpose of calling System.exit() in java

7.6k Views Asked by At

I am in a little bit confusion with system.exit. I founded some things about from this link.

but I have some doubts in my mind. If I use system exit, what will happened to the created objects,variable and ect. Are everything get destroyed once I called system.exit? If "Yes" then why we force to the garbage collection before system.exit() ? If "No" how long the created objects are stored in the JVM (memory)? If run the program again after exit from system, what will happened to the previous objects if they not destroyed once I called System.exit();?

Thanks.

3

There are 3 best solutions below

0
On

I think in this case it is useful to think of the JVM as a program running on a computer. System.exit() terminates that program. Nothing within the program is kept by the computer's OS or the JVM runtime, though the program, of course, may write things to long-term storage. But variables, created objs, and etc. are all gone, and cannot be restored.

0
On

If I use system exit, what will happened to the created objects,variable and ect. Are everything get destroyed once I called system.exit?

Only user threads are destroyed by a System exit.

why we force to the garbage collection before system.exit() ?

We don't and it wouldn't be very useful as this might not do anything.

how long the created objects are stored in the JVM (memory)?

Until they are no longer needed and a clean up occurs, of the JVM really exits

If run the program again after exit from system, what will happened to the previous objects if they not destroyed once I called System.exit();?

They are destroyed when the program finishes. In any case, every program gets it's own new set of variables even if run multiple times. There is no sharing of variables between programs.

0
On

The short answer of what you should know about exit:

  • It's useful because it's the only way to set the exit status.

  • Generally the only place you should use it is at the end of a main method.

  • It results in JVM termination (killing the process, thus necessarily freeing all memory).