Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Handle logoff or shutdown on Windows and Linux

Is there a way for a Java GUI application to respond to system shutdown or logoff events, other than to use JNI? (On Windows, the JNI would use WM_QUERYENDSESSION, on Linux?)

The method should allow the program to prompt users to save, etc., and then continue the logoff process.

like image 830
Michael Brewer-Davis Avatar asked Jan 26 '09 21:01

Michael Brewer-Davis


3 Answers

As far as I know, there's no way in Java to catch the system shutdown or logoff events.

You can, however, catch when the JVM is terminating by adding a shutdown hook.

AWT's WindowAdapter also has a windowClosing event that you can override and hook to a window that you want to monitor. Swing inherits this; I believe SWT does as well. Be aware that you MUST manually dispose of the window if you override this event!

I believe that MS Windows will fire these events as it is closing. I believe a SIGTERM on Linux/UNIX does the same, although Linux will SIGKILL an app shortly afterwords if this is during shutdown.

like image 81
Powerlord Avatar answered Oct 19 '22 21:10

Powerlord


I think that Runtime.getRuntime().addShutdownHook should provide the functionality you need.

like image 45
laz Avatar answered Oct 19 '22 22:10

laz


You can schedule a Thread to be run on JVM shutdown - see addShutdownHook().

like image 1
avalys Avatar answered Oct 19 '22 21:10

avalys