Explain Codes LogoExplain Codes Logo

How to quit a Java app from within the program

java
shutdown-hooks
resource-management
thread-management
Alex KataevbyAlex Kataev·Dec 10, 2024
TLDR

To terminate a Java program, use the System.exit(0) method.

System.exit(0); // RIP dear app, you will be missed

In GUIs, dispose of all frames first to release resources. It’s like vacating your house before you blow it up:

for(Frame frame : Frame.getFrames()) { frame.dispose(); // Nothing to see here, move along } System.exit(0); // Going out with a bang!

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 accomplished
  • System.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:

try (Resource resource = new Resource()) { // Secret stuff happens here } // POOF! The resource is gone

And for that, a shutdown() method can come handy:

public void shutdown() { // Do the dishes, take out the trash }

Don't be a rebel! Use finally block if you want things to be clean even when something goes wrong:

try { // risky stuff here } finally { shutdown(); // tidy up after wild party }

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
thread.interrupt(); // You have been terminated

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
WindowEvent we = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(we); // Time to say goodbye

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:

Runtime.getRuntime().addShutdownHook(new Thread(() -> { // The last dance }));

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