Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 212
maXfenda Avatar asked Aug 12 '13 10:08

maXfenda


3 Answers

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.

like image 103
Peter Lawrey Avatar answered Nov 06 '22 06:11

Peter Lawrey


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.

like image 39
arcy Avatar answered Nov 06 '22 06:11

arcy


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

like image 31
Chris Martin Avatar answered Nov 06 '22 06:11

Chris Martin