2016-10-23 66 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,例如)