Cleaning before exiting a Java application

I am writing a small Java application using Swing. The application also has a network component.

I want to run some code before exiting (close channels, keys, etc.). Is there a way to do this without adding an Exit button to my interface to do my cleanup and then do System.exit ()?

+5
source share
3 answers

You can do what you want in windowClosing(), shown here .

+5
source

You can use the function Runtime#addShutdownHookto add a function to start when the JVM shuts down.

+8
source

Close Keys: SelectionKeys? You don’t have to do anything. Closing a channel automatically cancels all of its SelectionKeys. And if you do not have pending data that needs to be cleared, you also do not need to close the channels, the OS will do it for you.

+1
source

All Articles