栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java线程池:设置核心线程可超时被关闭(allowCoreThreadTimeOut)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java线程池:设置核心线程可超时被关闭(allowCoreThreadTimeOut)

目录
  • ThreadPoolExecutor
  • ThreadPoolTaskExecutor

ThreadPoolExecutor

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);
		}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/361865.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号