@Component
@Slf4j
public class DynamicThreadPoolFactory {
private static final String NAME_SPACE = "application";
/** 线程执行器 **/
private volatile ThreadPoolExecutor executor;
/** 核心线程数 **/
private Integer CORE_SIZE = 10;
/** 最大值线程数 **/
private Integer MAX_SIZE = 20;
/** 等待队列长度 **/
private Integer QUEUE_SIZE = 2000;
/** 线程存活时间 **/
private Long KEEP_ALIVE_TIME = 1000L;
private String REFRESH_CORE_SIZE_KEY ="refreshCoreSize";
private String REFRESH_MAX_SIZE_KEY ="refreshMaxSize";
/** 线程名 **/
private String threadName;
public DynamicThreadPoolFactory() {
Config config = ConfigService.getConfig(NAME_SPACE);
init(config);
listen(config);
}
/**
* 初始化
*/
private void init(Config config) {
if (executor == null) {
synchronized (DynamicThreadPoolFactory.class) {
if (executor == null) {
String coreSize = config.getProperty(REFRESH_CORE_SIZE_KEY, CORE_SIZE.toString());
String maxSize = config.getProperty(REFRESH_MAX_SIZE_KEY, MAX_SIZE.toString());
String keepAliveTime = KEEP_ALIVE_TIME.toString();
BlockingQueue<Runnable> queueToUse = new LinkedBlockingQueue<Runnable>(QUEUE_SIZE);
executor = new ThreadPoolExecutor(Integer.valueOf(coreSize), Integer.valueOf(maxSize), Long.valueOf(keepAliveTime), TimeUnit.MILLISECONDS, queueToUse, new NamedThreadFactory(threadName, true),new ThreadPoolExecutor.CallerRunsPolicy() );
}
}
}
}
/**
* 监听器
*/
private void listen(Config config) {
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
log.info("命名空间发生变化={}", changeEvent.getNamespace());
for (String key : changeEvent.changedKeys()) {
ConfigChange change = changeEvent.getChange(key);
String newValue = change.getNewValue();
refreshThreadPool(key, newValue);
log.info("发生变化key={},oldValue={},newValue={},changeType={}", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType());
}
}
});
}
/**
* 刷新线程池
*/
private void refreshThreadPool(String key, String newValue) {
if (executor == null) {
return;
}
if (REFRESH_CORE_SIZE_KEY.equals(key)) {
executor.setCorePoolSize(Integer.valueOf(newValue));
log.info("修改核心线程数key={},value={}", key, newValue);
}
if (REFRESH_MAX_SIZE_KEY.equals(key)) {
executor.setMaximumPoolSize(Integer.valueOf(newValue));
log.info("修改最大线程数key={},value={}", key, newValue);
}
}
public ThreadPoolExecutor getExecutor() {
return executor;
}
}
03-04
1957

11-26
1343

03-14
1657
