0

I have a standalone Java application that acts as a consumer that connects to an ActiveMQ queue. In my application's main() method, I create an instance of the consumer as a thread and start it.

Seeing that I'm using JMS for this, I want to add a shutdown hook to my application so that when my application stops working (either terminated or killed), my application would run some method wherein all my resources will be closed.

I already tried Runtime.addShutdownHook() but it doesn't seem to be invoked whenever I shut down my application.

I would like it to act as if the contextDestroyed() method of a ServletContextListener was invoked.

mpmp
  • 2,409
  • 4
  • 33
  • 46
  • How exactly are you shutting down your application? There is no way to add a hook that is guaranteed to run with every shutdown method; the OS can simply terminate the process of your application without allowing any code to run. – yole Jul 01 '15 at 20:41
  • Well, for now since I'm only developing, I use Eclipse to run and terminate my app. Once I finally package it in a JAR, I would most probably run it using a linux shell and terminate it using Ctrl+C. – mpmp Jul 01 '15 at 20:44
  • ```Runtime.addShutdownHook()``` will be invoked only in case of a graceful shutdown, i.e. when you do a CTRL+C or Kill, but if you do a hard shutdown, i.e. in the case of Kill -9, this shutdownHook will not be called. – Amm Sokun Jul 02 '15 at 17:58

1 Answers1

1

Runtime.addShutdownHook() is the correct API to use, but unfortunately the "Stop" button in Eclipse terminates the process without allowing any hooks to run. See Shutdown hook doesn't work in Eclipse for more information.

Community
  • 1
  • 1
yole
  • 92,896
  • 20
  • 260
  • 197
  • So are you saying that if I package my app as a just and run it independently from any IDE, the hook would work? – mpmp Jul 01 '15 at 20:55