¿Cómo apagar ThreadPoolExecutor en Spring Bean cuando Tomcat está apagado?

I create a threadpoolexecutor in a spring bean, so I need to shutdown this executor when tomcat is shutdown.

     public class PersistBO implements InitializingBean {

private ThreadPoolExecutor executer;

public void shutdownExecutor() {
    executer.shutdown();
}

@Override
public void afterPropertiesSet() throws Exception {
    taskQueue = new LinkedBlockingQueue<Runnable>(queueLength);
    executer = new ThreadPoolExecutor(minThread, maxThread, threadKeepAliveTime, 
            TimeUnit.SECONDS, taskQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
}

I have searched solution on google and get a result. That is to add a shutdownhook to java.lang.runtime. However, the java docs says java.lang.Runtime#shutdownHook is called when the last non-daemon thread exits. So it is a dead lock. Is there any solution to shutdown executor in spring bean?

preguntado el 31 de enero de 12 a las 08:01

Your pool can also use deamon threads, if you provide it with right thread factory. -

5 Respuestas

I guess lifecycle of the executor should depend on lifecycle of your application, not Tomcat as a whole. You can stop your application while Tomcat is still running, therefore Runtime.shutdownHook() no es aplicable.

Since you already use Spring and its InitializingBean for initialization, you can use DispasableBean to perform cleanup when application context is being closed:

public class PersistBO implements InitializingBean, DisposableBean { 
    public void destroy() {
        shutdownExecutor();
    }
    ...
}

Respondido el 31 de enero de 12 a las 13:01

Utilice el Runtime para agregar un gancho de apagado. Here's a very good tutorial by Heinz Kabutz: http://www.roseindia.net/javatutorials/hooking%20_into_the_shutdown_call.shtml

Respondido el 31 de enero de 12 a las 12:01

but the java docs says java.lang.Runtime#shutdownHook is called when the last non-daemon thread exits. Will it is a dead lock? - Simon Lin

Puedes implementar tu propio javax.servlet.ServletContextListener to be notified when your application is being shutdown and shutdown the pool from the listener.

Respondido el 31 de enero de 12 a las 13:01

Use the @Predestroy annotation on your shutdown method on the bean. this will result in spring calling this method when context is shutting down

Check if there is some executor service has a thread running in background. you can shutdown an executor by calling executor.shutdownNow().

ver también http://taranmeet.com/jvm-not-shutting-down-on-spring-context-close/

Respondido el 30 de Septiembre de 14 a las 05:09

Here is how to start and stop a thread in Spring bean.

    @PostConstruct
 public void init() {
  BasicThreadFactory factory = new BasicThreadFactory.Builder()
        .namingPattern("myspringbean-thread-%d").build();
  executorService =  Executors.newSingleThreadExecutor(factory);
  executorService.execute(new Runnable() {
   @Override
   public void run() {
    try {
     // do something
     System.out.println("thread started");
    } catch (Exception e) {
     logger.error("error: ", e);
    }

   }
  });
  executorService.shutdown();
 }


 @PreDestroy
 public void beandestroy() {
  if(executorService != null){
   executorService.shutdownNow();
  }
 }

Respondido el 14 de diciembre de 15 a las 19:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.