How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

后端 未结 5 908
眼角桃花
眼角桃花 2020-11-28 18:53

In a Spring web application I have several DAO and service layer beans. One service layer bean has annotated @Async / @Scheduled methods. These methods depend on other (auto

5条回答
  •  一个人的身影
    2020-11-28 19:14

    I had similar issues with the threads being started in Spring bean. These threads were not closing properly after i called executor.shutdownNow() in @PreDestroy method. So the solution for me was to let the thread finsih with IO already started and start no more IO, once @PreDestroy was called. And here is the @PreDestroy method. For my application the wait for 1 second was acceptable.

    @PreDestroy
        public void beandestroy() {
            this.stopThread = true;
            if(executorService != null){
                try {
                    // wait 1 second for closing all threads
                    executorService.awaitTermination(1, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    

    Here I have explained all the issues faced while trying to close threads.http://programtalk.com/java/executorservice-not-shutting-down/

提交回复
热议问题