2016-10-23 61 views
-1

我是新的弹簧与ExecutorService。请你确认下面的代码吗?我在@PostConstruct方法initailized ExecutorSerive并在@PreDestroy method.Is destoryed它有一个需要调用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(); 
    } 
} 
} 

回答

0

这取决于您的需求。正如java-doc清楚地指出关机方法:

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

wheras shutdownNow会尝试停止当前正在运行的任务。尝试意味着“尽力而为”。任务的执行必须合作,对内部的“停​​止”请求(通常由Thread.interrupt完成)做出适当的反应。

无论是关闭还是shutdownNow时等待运行的任务(线程)真的终止。一个java程序只有在最后一个线程终止时才会完全终止,而不仅仅是主线程。 (当然,依赖于线程守护标志的设置。但因为你靠一个默认的执行实现,你没有这个控制下不使用的ThreadPoolExecutor时提供自定义的ThreadFactory,例如)