【问题标题】:Spring with Executor service带有 Executor 服务的 Spring
【发布时间】:2016-10-23 12:37:50
【问题描述】:

我是 ExecutorService 的 Spring 新手。请问你能确认下面的代码吗?我已经在@PostConstruct 方法中初始化了ExecutorSerive,并在@PreDestroy 方法中对其进行了破坏。是否需要调用shutdownNow()。如果有,会在哪里?

private static final int FIXED_THREAD_POOL_SIZE =3;

private static final Log LOGGER = LogFactory.getLog(HotelProgramInfoHistoryService.class);

private ExecutorService executorService;


@PostConstruct
public void initialize() throws Exception {

    if(executorService == null) {
        this.executorService = Executors.newFixedThreadPool(FIXED_THREAD_POOL_SIZE);
    }
}

public void sendRequest(DomainSecurity security, HotelProgramInfo hotelProgramInfo) {

    try {
        ProgramInfoHistoryUpdateTask programInfoHistoryUpdateTask = new ProgramInfoHistoryUpdateTask(hotelProgramInfo);
        this.executorService.submit(programInfoHistoryUpdateTask);
    } catch (Exception exception) {
        LOGGER.error("Exception occurred while submitting update task ", exception);
    }

}

@PreDestroy
public void cleanUp() throws Exception {
    if(executorService != null)
    {
        executorService.shutdown();
    }
}
}

【问题讨论】:

    标签: java spring multithreading


    【解决方案1】:

    这取决于您的需求。正如 java-doc 明确说明的关闭方法:

    ... previously submitted
    tasks are executed, but no new tasks will be accepted
    

    而 shutdownNow 尝试停止当前正在运行的任务。尝试意味着“尽力而为”。任务的实现必须配合才能正确响应来自外部的“停止”请求(通常由 Thread.interrupt 完成)。

    shutdown 和 shutdownNow 都不会等到正在运行的任务(线程)真正终止。 java程序只有在最后一个线程终止时才会完全终止,而不仅仅是主线程。 (嗯,取决于 Threads 守护进程标志的设置。但是由于您依赖于默认执行器实现,因此如果不提供自定义 ThreadFactory,例如使用 ThreadPoolExecutor 时,您将无法控制它)

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 1970-01-01
      • 2015-03-05
      • 2012-06-19
      • 2017-01-10
      • 1970-01-01
      • 2013-09-27
      • 2020-07-01
      • 2015-08-16
      相关资源
      最近更新 更多