Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java spring是否负责关闭您的Executor服务?_Java_Spring_Executorservice_Shutdown - Fatal编程技术网

Java spring是否负责关闭您的Executor服务?

Java spring是否负责关闭您的Executor服务?,java,spring,executorservice,shutdown,Java,Spring,Executorservice,Shutdown,在我的配置类中,我有一个用于FixedThreadPool的bean @Bean public ExecutorService fixedThreadPool() { return Executors.newFixedThreadPool(200); } 后来我在某节课上自动连线。在我研究的过程中,我发现这是关闭executor服务的最佳方式,如 但我也发现,如果你的ExecutorService是一个bean。我的问题是——这是真的吗?如果是的话,肯定会更容易,因为我不知道把上面提到

在我的配置类中,我有一个用于FixedThreadPool的bean

@Bean
public ExecutorService fixedThreadPool() {
    return Executors.newFixedThreadPool(200);
}
后来我在某节课上自动连线。在我研究的过程中,我发现这是关闭executor服务的最佳方式,如


但我也发现,如果你的ExecutorService是一个bean。我的问题是——这是真的吗?如果是的话,肯定会更容易,因为我不知道把上面提到的代码放在哪里。如果我把它放在我正在使用这个bean的类中,我将来可能会在其他一些类中使用这个bean,而这似乎是错误的

是的,Spring会为您这样做,但它只会在容器关闭时销毁bean,您可能希望在执行服务处理完所有任务后关闭它。您可以创建ExecutorServiceBean作为原型,但由于spring不会完全管理其生命周期,所以一旦您的任务完成,您就必须自己调用它的destroy方法

它是怎么做到的?它是否对
ExecutorService
有特殊支持,这样您就不必自己指定任何生命周期方法了?回答我自己的问题:默认情况下,Spring在
@Bean
上查找
close()
shutdown()
方法。除非您以其他方式配置它,否则它将调用它们。@Raghvendra From,我认为如果在我的例子中bean的作用域是prototype,Spring不会为我关闭。如果我错了,请纠正我。我指的是本节最后一段的下一段。@Melissagren是的,我被更正了。spring不会完全管理原型bean的生命周期
   void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }