Spring与Executor服务

时间:2016-10-23 12:37:50

标签: java spring multithreading

我是ExecutorService的新手。你能否确认下面的代码?我已使用ExecutorSerive方法初始化了@PostConstruct,并使用@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();
    }
}
}

1 个答案:

答案 0 :(得分:0)

这取决于您的需求。正如java-doc明确指出了shutdown方法:

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

当shutdownNow尝试停止当前正在运行的任务时。尝试意味着最好的努力"。任务的实施必须合作,以便在“停止”#34;来自ouside的请求(通常由Thread.interrupt完成)。

在正常运行的任务(线程)被终止之前,shutdown和shutdownNow都不会等待。如果最后一个线程已终止,则java程序仅完全终止,而不仅仅是主线程。 (好吧,取决于Threads守护程序标志的设置。但是因为你依赖于一个默认的执行程序实现,所以你没有提供自定义ThreadFactory就可以控制它,例如在使用ThreadPoolExecutor时)