How to quit a Java app from within the program
To terminate a Java program, use the System.exit(0)
method.
In GUIs, dispose of all frames first to release resources. It’s like vacating your house before you blow it up:
Clean up before you exit, this isn't a wild party!
Understand System.exit()
The quick and dirty way to terminate a Java program is System.exit()
. Here's the thing about System.exit()
, it takes an argument - status code.
System.exit(0);
means all is well, mission accomplishedSystem.exit(non-zero);
means Houston, we had a problem
What about Resources?
Like a spy leaving no trace behind, your application should release open resources like files, sockets, and connections:
And for that, a shutdown()
method can come handy:
Don't be a rebel! Use finally
block if you want things to be clean even when something goes wrong:
Dealing with background threads
In the shadows, background threads keep the application alive:
- Yell
interrupt()
for them to terminate - Have
Thread.isInterrupted()
so they know when to duck out
Make sure you also take care of non-daemon threads, they're sticky.
If your app is a GUI
GUI applications need a soft touch:
- Stop the event loop
- Summon a window closing event to gently walk the application out the door
When to avoid System.exit()
You might want to avoid System.exit()
if it could risk data loss, or if you are in a container or framework that expects a more civil exit.
Instead, you can try out shutdown hooks:
Extra care when exiting
Show a little love before you leave:
- Clean-up background processes
- Make sure data is consistent
- Let everyone know that you are leaving
Proper way to bow out
Before you show yourself the exit door:
- Save the user's preferences and state
- Make sure you commit on the database transactions
- Remember to logout of the authentication servers
Design and shutdown, together forever
Your design patterns and architecture can make shutdown process easier:
- Observer pattern for some wave goodbye
- Strategy pattern for the different exit strategies
- Well organized resource management to take care of the mess
Test, test, and test again
Test your shutdown procedure to find and fix:
- Resources pretending to be a clingy ex
- Deadlocks that refuse to break up
- How long to wait (Timeouts) before finalizing the divorce
Say goodbye to your components
Make sure you say goodbye properly:
- Event-driven messaging for a coordinated retreat
- Flags and semaphores for signaling between comrades
- Prioritize your goodbyes
Was this article helpful?