Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

In Java, What is the difference with or without System.exit(0) in following code?

public class TestExit

{      

    public static void main(String[] args)

    { 

        System.out.println("hello world");

        System.exit(0);  // is it necessary? And when it must be called? 

    }      

}

The document says: "This method never returns normally." What does it mean?

1 Answer

0 votes
by (46k points)
System.exit() can be used to run shutdown hooks before the program quits. This is a convenient way to handle shutdown in bigger programs, where all parts of the program can't (and shouldn't) be aware of each other. Then, if someone wants to quit, he can simply call System.exit(), and the shutdown hooks (if properly set up) take care of doing all necessary shutdown ceremonies such as closing files, releasing resources etc.

"This method never returns normally." means just that the method won't return; once a thread goes there, it won't come back.

Another, maybe more common, way to quit a program is to simply to reach the end of the main method. But if there are any non-daemon threads running, they will not be shut down and thus the JVM will not exit. Thus, if you have any such non-daemon threads, you need some other means (than the shutdown hooks) to shut down all non-daemon threads and release other resources. If there are no other non-daemon threads, returning from main will shut down the JVM and will call the shutdown hooks.

For some reason shutdown hooks seem to be an undervalued and misunderstood mechanism, and people are reinventing the wheel with all kind of proprietary custom hacks to quit their programs. I would encourage using shutdown hooks; it's all there in the standard Runtime that you'll be using anyway.

Related questions

0 votes
1 answer
asked Sep 29, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...