服务异常终止时,服务内部的线程池中的任务是否需要运行完成,如需要,则增加以下代码,等待任务执行完成后(时间可设置)再销毁
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 优雅关闭线程池
*/
@Component
public class ThreadPoolExecutorShutdownDefinition implements ApplicationListener<ContextClosedEvent> {
private static final Logger logger = LoggerFactory.getLogger(ThreadPoolExecutorShutdownDefinition.class);
private final List<ExecutorService> POOLS = Collections.synchronizedList(new ArrayList<>(12));
/**
* 线程中的任务在接收到应用关闭信号量后最多等待多久就强制终止,其实就是给剩余任务预留的时间, 到时间后线程池必须销毁
*/
private final long AWAIT_TERMINATION = 20;
/**
* awaitTermination的单位
*/
private final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
public void registryExecutor(ExecutorService executor) {
POOLS.add(executor);
}
/**
* 参考{@link org.springframework.scheduling.concurrent.ExecutorConfigurationSupport#shutdown()}
*
* @param event the event to respond to
*/
@Override
public void onApplicationEvent(ContextClosedEvent event) {
logger.info("graceful shutdown thread pool start, current pool nums: {} >>>>>>>>>>>>>>>>", POOLS.size());
if (CollectionUtils.isEmpty(POOLS)) {
return;
}
for (ExecutorService pool : POOLS) {
pool.shutdown();
try {
if (!pool.awaitTermination(AWAIT_TERMINATION, TIME_UNIT)) {
if (logger.isWarnEnabled()) {
logger.warn("Timed out while waiting for executor [{}] to terminate", pool);
}
}
} catch (InterruptedException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Timed out while waiting for executor [{}] to terminate", pool);
}
Thread.currentThread().interrupt();
}
}
}
}
使用,注册线程池
shutdownDefinition.registryExecutor(executor);