Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get my Java application to shutdown nicely in windows?

I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it.

I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely?

like image 908
Free Wildebeest Avatar asked Sep 14 '08 22:09

Free Wildebeest


2 Answers

The previously mentioned JNI approach will likely work.

You can use JNA which is basically a wrapper around JNI to make it easier to use. An added bonus is that it (in my opinion at least) generally is faster and more maintainable than raw JNI. You can find JNA at https://jna.dev.java.net/

If you're just starting the application in the start menu because you're trying to make it behave like a service in windows, you can use the java service wrapper which is found here: http://wrapper.tanukisoftware.org/doc/english/download.jsp

like image 140
Steve g Avatar answered Sep 17 '22 16:09

Steve g


As far as I know you need to start using JNI to set up a message handler for the Windows WM_QUERYENDSESSION message.

To do this (if you're new to Windows programming like me) you'll need to create a new class of window with a new message handling function (as described here) and handle the WM_QUERYENDSESSION from the message handler.

NB: You'll need to use the JNIEnv::GetJavaVM(...) and then JavaVM::AttachCurrentThread(...) on the message handling thread before you can call any Java methods from your native message handling code.

like image 21
Free Wildebeest Avatar answered Sep 16 '22 16:09

Free Wildebeest