Reputation: 75619
More specifically, I have a multithreaded command line Java application which runs and collects data until the user terminates it.
The obvious way for the user to terminate it is by pushing Control-C, but then I need to install a shutdown hook in the VM and deal with all the threads.
Is there a nicer / more appropriate way for the user to inform the application that it's time to shutdown?
For example, is there a way to capture some other key combination and set a boolean flag in my application?
As a further clarification, I seek something functionally similar to signal handling in C.
Upvotes: 3
Views: 545
Reputation: 12585
Is there a nicer / more appropriate way for the user to inform the application that it's time to shutdown?
The best way is to use Java Monitoring and Management
Look at this post for example.
It is best not to rely on shutdown hook.Shutdown hook in java works for KILL -15
AND KILL
and do not work for KILL -9
(HARD KILL)
Upvotes: 1
Reputation: 786001
Consider using shutdown hook like this:
Runtime.getRuntime().addShutdownHook(shutdownHook);
to have your own code that runs whenever the JVM terminates under 1 of the following conditions:
You can refer to: http://www.ibm.com/developerworks/ibm/library/i-signalhandling/ for more details (Disclaimer: very old article pertains to JDK 1.3.1)
Upvotes: 1
Reputation: 72835
This is not a Java specific solution but (atleast on Linux) during shutdown, the operating system sends a SIGTERM
to all processes (following by a SIGKILL after a grace period). Your application should install a handler for this and then shutdown gracefully. Once you do this, it will automatically take care of itself when you shutdown your VM.
Upvotes: 0
Reputation: 3968
One way can be to create a new thread which will "listen" to standard input. Based on whatever key pattern you decide, that thread can set the flag in the main application.
Upvotes: 2