简体   繁体   English

如何在Resteasy中关闭ExecutorService

[英]How to shutdown ExecutorService in Resteasy

I have a servlet that has an ExecutorService that makes HTTP requests to multiple destinations. 我有一个具有ExecutorService的servlet,该服务向多个目标发出HTTP请求。 I'm not sure how I shutdown the ExecutorService. 我不确定如何关闭ExecutorService。 I don't have destroy() method in Resteasy? 我在Resteasy中没有destroy()方法?

@Path("ops")
public class Dashboard{

ExecutorService threadExecutor = Executors.newCachedThreadPool();

@GET
@Path("data")
@Produces("application/json")
public Response getDataFromDCs(){
  try{
    threadExecutor.invokeAll(jobWorkers, 6000, TimeUnit.SECONDS);
  }catch(Exception e){}
  finally{
  //should call threadExecutor.shutdown() here? 
  }
}
}

You can create a Singleton Class that will have executor Service logic initiated , a destroy method and a service(jobWorker,int time,TimeUnit timeunit). 您可以创建一个Singleton类,该类将启动执行程序服务逻辑,销毁方法和服务(jobWorker,int时间,TimeUnit时间单位)。 Then write a Listener implementing HTTPServletListener and in contextDestroyed call the destroy method of the singleton class. 然后编写一个实现HTTPServletListener的侦听器,并在contextDestroyed中调用单例类的destroy方法。 This will save you from reinitiating executor on each service call and you can safely shutdown the executor on application shutdown. 这样可以避免您在每次服务调用时重新启动执行程序,并且可以在应用程序关闭时安全地关闭执行程序。 and in the webservice class in getDataFromDCs() get the instance of the singleton class and call it's service method passing the arguments. getDataFromDCs()的webservice类中,获取单例类的实例,并调用其传递参数的service方法。

you can call shutdown method of the threadExecutor. 您可以调用threadExecutor的关闭方法。 But it does not guarantee that all the task will finish. 但这不能保证所有任务都会完成。 You should also use awaitTermination, for example: 您还应该使用awaitTermination,例如:

while( !executor.awaitTermination(100, TimeUnit.SECONDS) ) {
    LOGGER.info("Awaiting completion of threads.");
}

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination(long,%20java.util.concurrent.TimeUnit) http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination(long,%20java.util.concurrent.TimeUnit)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM