0

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.

  1. 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)?

  2. May i add multiple thread to listen for this event?

Michael
  • 2,827
  • 4
  • 30
  • 47
  • On Unix systems, Ctrl+D ends the standard input. Ctrl+whatever is handled by the terminal. So you can't hook Ctrl+whatever in the Java program. – ignis Oct 29 '12 at 13:28
  • 2
    Possible duplicate: http://stackoverflow.com/questions/1028687/best-way-to-gracefully-shutdown-a-java-command-line-program – beny23 Oct 29 '12 at 13:35
  • @ignis: CTRL^* IS NOT MUST, any other combination is welcome – Michael Oct 29 '12 at 13:37
  • @beny23: +1,Thanks , i missed this post, hope it will help, i'll go over it now – Michael Oct 29 '12 at 13:38
  • @beny23: Please see my EDIT, i am sorry that i have updated the question and i probably had to open a new one, i will really appreciate an answer to the extended question. – Michael Oct 29 '12 at 14:55

1 Answers1

1

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!");
    }
});
Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
  • Thanks, i have read this solution in the post in the comment supplied by beny23 – Michael Oct 29 '12 at 14:12
  • Please see my EDIT, i am sorry that i have updated the question and i probably had to open a new one, i will really appreciate if you can extend your answer. – Michael Oct 29 '12 at 14:54