0

i saw some code use ShutdownHook like this

Runtime.getRuntime().addShutdownHook(new Thread(){
    ConfigurableApplicationContext.stop();
    //close spring context;
    threadpool.shutdownnow();
    //close theadpool
});

is there anything useful to do like this?

i thought

when jvm exit ,maybe thread will be shutdown immediately and spring context will close tooï¼›

what shall we do next when we need to call System.exit() ?

martin
  • 1
  • 1

1 Answers1

0

It really depends on your application and the lifecycle of your objects and those threads you appear to have outside of your context. If you are running the spring container inside a standalone java process, then trapping the shutdown hook like this is one way to do that. Another way is to have it listen on a tcp port and send a command to begin the shutdown process. If you are running in a web container like tomcat, then you should follow the standards on normal webapp shutdown, which Spring supports with Context Listeners.

I would also consider redesigning your app so that the threads are all managed with a bean that lives inside your spring container. For instance using a bean that is configured with directives (attributes) for start/stop methods and then that bean would use an Executor for thread pooling. This way, your shutdown is ONLY shutting down the Spring container, and Spring provides very good support for orderly shutdown of beans. One of those beans is your object holding the threads within the Executor. Its a much cleaner way than trying to integrate Spring beans with external threads.

Hope this helps.

Jerico Sandhorn
  • 1,880
  • 1
  • 18
  • 24