Reputation: 2867
I have developed a Java online distributed application which usually active all the time (not GUI).
I am interested to perform some steps before the shutdown in case the administrator is interested in such shutdown.
I know that CTRL^C stops the JVM, i wonder if i can hook CTRL^C and execute some additional operations before JVM shutdown, or add some hook to a CTRL^D event in order to do the same thing.
I almost sure there is a post somewhere describes similar questions , and i would appreciate links to such posts.
i am not interested in any third party external jars or any JNI solution.
I will appreciated a code example snippet if there is no post discussing the same question.
Additional constraint: This solution should work both for UNIX and Windows.
Edit
One solution that was proposed here is the use of Runtime.getRuntime().addShutdownHook(new Thread() {})
As far as i understand a new thread is created which will listen and wait to the shutdown event to happen.
I wonder if somehow i can signal the main thread that a shutdown occurred ( I have a distributed system as i mentioned , and i need to inform each single thread of such event)?
May i add multiple thread to listen for this event?
Upvotes: 0
Views: 395
Reputation: 10998
To react to CTRL+C you have to add a shutdown hook:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("I'll be back!");
}
});
Upvotes: 1