- ThreadPoolExecutor
- ThreadPoolTaskExecutor
Java线程池可以设置核心线程也随超时时间关闭,节省资源
java.util.concurrent.ThreadPoolExecutor
private volatile boolean allowCoreThreadTimeOut;
public void allowCoreThreadTimeOut(boolean value) {
if (value && keepAliveTime <= 0)
throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
if (value != allowCoreThreadTimeOut) {
allowCoreThreadTimeOut = value;
if (value)
interruptIdleWorkers();
}
}
ThreadPoolTaskExecutor
spring带的线程池可以设置,归根到底也是调用原生线程池的方法org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
他有一个属性allowCoreThreadTimeOut ,将其设为true,则可以控制coresize核心线程也能被关闭
private boolean allowCoreThreadTimeOut = false;
public void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) {
this.allowCoreThreadTimeOut = allowCoreThreadTimeOut;
}
ThreadPoolTaskExecutor设置处
if (this.taskDecorator != null) {
executor = new ThreadPoolExecutor(
this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, TimeUnit.SECONDS,
queue, threadFactory, rejectedExecutionHandler) {
@Override
public void execute(Runnable command) {
Runnable decorated = taskDecorator.decorate(command);
if (decorated != command) {
decoratedTaskMap.put(decorated, command);
}
super.execute(decorated);
}
};
}
else {
executor = new ThreadPoolExecutor(
this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, TimeUnit.SECONDS,
queue, threadFactory, rejectedExecutionHandler);
}
if (this.allowCoreThreadTimeOut) {
executor.allowCoreThreadTimeOut(true);
}



