Core code refactoring

pull/218/head
chen.ma 3 years ago
parent b281c150c1
commit 8d00d6e839

@ -0,0 +1,22 @@
package cn.hippo4j.common.constant;
/**
* Change thread-pool constants.
*
* @author chen.ma
* @date 2022/5/1 17:25
*/
public class ChangeThreadPoolConstants {
public static final String CHANGE_THREAD_POOL_TEXT = "[{}] Changed thread pool. " +
"\n coreSize :: [{}]" +
"\n maxSize :: [{}]" +
"\n queueType :: [{}]" +
"\n capacity :: [{}]" +
"\n keepAliveTime :: [{}]" +
"\n executeTimeOut :: [{}]" +
"\n rejectedType :: [{}]" +
"\n allowCoreThreadTimeOut :: [{}]";
public static final String CHANGE_DELIMITER = "%s => %s";
}

@ -87,5 +87,4 @@ public interface BootstrapPropertiesInterface {
default Boolean getBanner() { default Boolean getBanner() {
return null; return null;
} }
} }

@ -39,5 +39,4 @@ public class ConfigEmptyException extends RuntimeException {
* action * action
*/ */
private String action; private String action;
} }

@ -37,5 +37,4 @@ public class UtilAutoConfiguration {
public InetUtils hippo4JInetUtils(InetUtilsProperties properties) { public InetUtils hippo4JInetUtils(InetUtilsProperties properties) {
return new InetUtils(properties); return new InetUtils(properties);
} }
} }

@ -77,5 +77,4 @@ public class WebThreadPoolConfiguration {
public WebThreadPoolHandlerChoose webThreadPoolServiceChoose() { public WebThreadPoolHandlerChoose webThreadPoolServiceChoose() {
return new WebThreadPoolHandlerChoose(); return new WebThreadPoolHandlerChoose();
} }
} }

@ -51,35 +51,30 @@ public class BeforeCheckConfiguration {
"Web server failed to start. The dynamic thread pool username is empty.", "Web server failed to start. The dynamic thread pool username is empty.",
"Please check whether the [spring.dynamic.thread-pool.username] configuration is empty or an empty string."); "Please check whether the [spring.dynamic.thread-pool.username] configuration is empty or an empty string.");
} }
String password = properties.getPassword(); String password = properties.getPassword();
if (StringUtil.isBlank(password)) { if (StringUtil.isBlank(password)) {
throw new ConfigEmptyException( throw new ConfigEmptyException(
"Web server failed to start. The dynamic thread pool password is empty.", "Web server failed to start. The dynamic thread pool password is empty.",
"Please check whether the [spring.dynamic.thread-pool.password] configuration is empty or an empty string."); "Please check whether the [spring.dynamic.thread-pool.password] configuration is empty or an empty string.");
} }
String namespace = properties.getNamespace(); String namespace = properties.getNamespace();
if (StringUtil.isBlank(namespace)) { if (StringUtil.isBlank(namespace)) {
throw new ConfigEmptyException( throw new ConfigEmptyException(
"Web server failed to start. The dynamic thread pool namespace is empty.", "Web server failed to start. The dynamic thread pool namespace is empty.",
"Please check whether the [spring.dynamic.thread-pool.namespace] configuration is empty or an empty string."); "Please check whether the [spring.dynamic.thread-pool.namespace] configuration is empty or an empty string.");
} }
String itemId = properties.getItemId(); String itemId = properties.getItemId();
if (StringUtil.isBlank(itemId)) { if (StringUtil.isBlank(itemId)) {
throw new ConfigEmptyException( throw new ConfigEmptyException(
"Web server failed to start. The dynamic thread pool item id is empty.", "Web server failed to start. The dynamic thread pool item id is empty.",
"Please check whether the [spring.dynamic.thread-pool.item-id] configuration is empty or an empty string."); "Please check whether the [spring.dynamic.thread-pool.item-id] configuration is empty or an empty string.");
} }
String serverAddr = properties.getServerAddr(); String serverAddr = properties.getServerAddr();
if (StringUtil.isBlank(serverAddr)) { if (StringUtil.isBlank(serverAddr)) {
throw new ConfigEmptyException( throw new ConfigEmptyException(
"Web server failed to start. The dynamic thread pool server addr is empty.", "Web server failed to start. The dynamic thread pool server addr is empty.",
"Please check whether the [spring.dynamic.thread-pool.server-addr] configuration is empty or an empty string."); "Please check whether the [spring.dynamic.thread-pool.server-addr] configuration is empty or an empty string.");
} }
String applicationName = environment.getProperty("spring.application.name"); String applicationName = environment.getProperty("spring.application.name");
if (StringUtil.isBlank(applicationName)) { if (StringUtil.isBlank(applicationName)) {
throw new ConfigEmptyException( throw new ConfigEmptyException(
@ -94,5 +89,4 @@ public class BeforeCheckConfiguration {
public class BeforeCheck { public class BeforeCheck {
} }
} }

@ -37,5 +37,4 @@ public class MarkerConfiguration {
public class Marker { public class Marker {
} }
} }

@ -71,11 +71,9 @@ public class DynamicThreadPoolExecutor extends AbstractDynamicExecutorSupport {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, waitForTasksToCompleteOnShutdown, awaitTerminationMillis, workQueue, threadPoolId, threadFactory, handler); super(corePoolSize, maximumPoolSize, keepAliveTime, unit, waitForTasksToCompleteOnShutdown, awaitTerminationMillis, workQueue, threadPoolId, threadFactory, handler);
this.threadPoolId = threadPoolId; this.threadPoolId = threadPoolId;
this.executeTimeOut = executeTimeOut; this.executeTimeOut = executeTimeOut;
// Number of dynamic proxy denial policies. // Number of dynamic proxy denial policies.
RejectedExecutionHandler rejectedProxy = RejectedProxyUtil.createProxy(handler, threadPoolId, rejectCount); RejectedExecutionHandler rejectedProxy = RejectedProxyUtil.createProxy(handler, threadPoolId, rejectCount);
setRejectedExecutionHandler(rejectedProxy); setRejectedExecutionHandler(rejectedProxy);
// Redundant fields to avoid reflecting the acquired fields when sending change information. // Redundant fields to avoid reflecting the acquired fields when sending change information.
redundancyHandler = handler; redundancyHandler = handler;
} }

@ -35,83 +35,29 @@ import java.util.concurrent.ThreadPoolExecutor;
@Data @Data
public class DynamicThreadPoolWrapper implements DisposableBean { public class DynamicThreadPoolWrapper implements DisposableBean {
/** private String tenantId, itemId, threadPoolId;
* Tenant id
*/
private String tenantId;
/** private boolean subscribeFlag, initFlag;
* Item id
*/
private String itemId;
/**
* Thread pool id
*/
private String tpId;
/**
* Subscribe flag
*/
private boolean subscribeFlag;
/**
* Init flag
*/
private boolean initFlag;
/**
* executor
* {@link DynamicThreadPoolExecutor}
*/
private ThreadPoolExecutor executor; private ThreadPoolExecutor executor;
/**
* 线, 使线 {@link CommonDynamicThreadPool#getInstance(String)}
*
* @param threadPoolId
*/
public DynamicThreadPoolWrapper(String threadPoolId) { public DynamicThreadPoolWrapper(String threadPoolId) {
this(threadPoolId, CommonDynamicThreadPool.getInstance(threadPoolId)); this(threadPoolId, CommonDynamicThreadPool.getInstance(threadPoolId));
} }
/**
* 线, 使 threadPoolExecutor.
*
* @param threadPoolId
* @param threadPoolExecutor
*/
public DynamicThreadPoolWrapper(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) { public DynamicThreadPoolWrapper(String threadPoolId, ThreadPoolExecutor threadPoolExecutor) {
this.tpId = threadPoolId; this.threadPoolId = threadPoolId;
this.executor = threadPoolExecutor; this.executor = threadPoolExecutor;
} }
/**
* .
*
* @param command
*/
public void execute(Runnable command) { public void execute(Runnable command) {
executor.execute(command); executor.execute(command);
} }
/**
* .
*
* @param task
* @return
*/
public Future<?> submit(Runnable task) { public Future<?> submit(Runnable task) {
return executor.submit(task); return executor.submit(task);
} }
/**
* .
*
* @param task
* @param <T>
* @return
*/
public <T> Future<T> submit(Callable<T> task) { public <T> Future<T> submit(Callable<T> task) {
return executor.submit(task); return executor.submit(task);
} }
@ -122,5 +68,4 @@ public class DynamicThreadPoolWrapper implements DisposableBean {
((AbstractDynamicExecutorSupport) executor).destroy(); ((AbstractDynamicExecutorSupport) executor).destroy();
} }
} }
} }

@ -107,10 +107,8 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
if (hippoSendMessageService == null) { if (hippoSendMessageService == null) {
return; return;
} }
ThreadPoolNotifyAlarm threadPoolNotifyAlarm = GlobalNotifyAlarmManage.get(threadPoolId); ThreadPoolNotifyAlarm threadPoolNotifyAlarm = GlobalNotifyAlarmManage.get(threadPoolId);
BlockingQueue blockIngQueue = threadPoolExecutor.getQueue(); BlockingQueue blockIngQueue = threadPoolExecutor.getQueue();
int queueSize = blockIngQueue.size(); int queueSize = blockIngQueue.size();
int capacity = queueSize + blockIngQueue.remainingCapacity(); int capacity = queueSize + blockIngQueue.remainingCapacity();
int divide = CalculateUtil.divide(queueSize, capacity); int divide = CalculateUtil.divide(queueSize, capacity);
@ -133,7 +131,6 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
int activeCount = threadPoolExecutor.getActiveCount(); int activeCount = threadPoolExecutor.getActiveCount();
int maximumPoolSize = threadPoolExecutor.getMaximumPoolSize(); int maximumPoolSize = threadPoolExecutor.getMaximumPoolSize();
int divide = CalculateUtil.divide(activeCount, maximumPoolSize); int divide = CalculateUtil.divide(activeCount, maximumPoolSize);
ThreadPoolNotifyAlarm threadPoolNotifyAlarm = GlobalNotifyAlarmManage.get(threadPoolId); ThreadPoolNotifyAlarm threadPoolNotifyAlarm = GlobalNotifyAlarmManage.get(threadPoolId);
boolean isSend = threadPoolNotifyAlarm.getIsAlarm() boolean isSend = threadPoolNotifyAlarm.getIsAlarm()
&& divide > threadPoolNotifyAlarm.getActiveAlarm(); && divide > threadPoolNotifyAlarm.getActiveAlarm();
@ -154,7 +151,6 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
if (Objects.isNull(threadPoolNotifyAlarm) || !threadPoolNotifyAlarm.getIsAlarm()) { if (Objects.isNull(threadPoolNotifyAlarm) || !threadPoolNotifyAlarm.getIsAlarm()) {
return; return;
} }
ThreadPoolExecutor threadPoolExecutor = GlobalThreadPoolManage.getExecutorService(threadPoolId).getExecutor(); ThreadPoolExecutor threadPoolExecutor = GlobalThreadPoolManage.getExecutorService(threadPoolId).getExecutor();
checkPoolRejectedAlarm(threadPoolId, threadPoolExecutor); checkPoolRejectedAlarm(threadPoolId, threadPoolExecutor);
} }
@ -186,19 +182,16 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
if (Objects.isNull(threadPoolNotifyAlarm) || !threadPoolNotifyAlarm.getIsAlarm()) { if (Objects.isNull(threadPoolNotifyAlarm) || !threadPoolNotifyAlarm.getIsAlarm()) {
return; return;
} }
if (threadPoolExecutor instanceof DynamicThreadPoolExecutor) { if (threadPoolExecutor instanceof DynamicThreadPoolExecutor) {
try { try {
AlarmNotifyRequest alarmNotifyRequest = buildAlarmNotifyReq(threadPoolExecutor); AlarmNotifyRequest alarmNotifyRequest = buildAlarmNotifyReq(threadPoolExecutor);
alarmNotifyRequest.setThreadPoolId(threadPoolId); alarmNotifyRequest.setThreadPoolId(threadPoolId);
alarmNotifyRequest.setExecuteTime(executeTime); alarmNotifyRequest.setExecuteTime(executeTime);
alarmNotifyRequest.setExecuteTimeOut(executeTimeOut); alarmNotifyRequest.setExecuteTimeOut(executeTimeOut);
String executeTimeoutTrace = TraceContextUtil.getAndRemove(); String executeTimeoutTrace = TraceContextUtil.getAndRemove();
if (StringUtil.isNotBlank(executeTimeoutTrace)) { if (StringUtil.isNotBlank(executeTimeoutTrace)) {
alarmNotifyRequest.setExecuteTimeoutTrace(executeTimeoutTrace); alarmNotifyRequest.setExecuteTimeoutTrace(executeTimeoutTrace);
} }
Runnable task = () -> hippoSendMessageService.sendAlarmMessage(NotifyTypeEnum.TIMEOUT, alarmNotifyRequest); Runnable task = () -> hippoSendMessageService.sendAlarmMessage(NotifyTypeEnum.TIMEOUT, alarmNotifyRequest);
EXECUTE_TIMEOUT_EXECUTOR.execute(task); EXECUTE_TIMEOUT_EXECUTOR.execute(task);
} catch (Throwable ex) { } catch (Throwable ex) {
@ -217,7 +210,6 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
String appName = StrUtil.isBlank(itemId) ? applicationName : itemId; String appName = StrUtil.isBlank(itemId) ? applicationName : itemId;
request.setAppName(appName); request.setAppName(appName);
request.setIdentify(IdentifyUtil.getIdentify()); request.setIdentify(IdentifyUtil.getIdentify());
hippoSendMessageService.sendChangeMessage(request); hippoSendMessageService.sendChangeMessage(request);
} }
@ -229,10 +221,8 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
*/ */
public AlarmNotifyRequest buildAlarmNotifyReq(ThreadPoolExecutor threadPoolExecutor) { public AlarmNotifyRequest buildAlarmNotifyReq(ThreadPoolExecutor threadPoolExecutor) {
AlarmNotifyRequest request = new AlarmNotifyRequest(); AlarmNotifyRequest request = new AlarmNotifyRequest();
String appName = StrUtil.isBlank(itemId) ? applicationName : itemId; String appName = StrUtil.isBlank(itemId) ? applicationName : itemId;
request.setAppName(appName); request.setAppName(appName);
// 核心线程数 // 核心线程数
int corePoolSize = threadPoolExecutor.getCorePoolSize(); int corePoolSize = threadPoolExecutor.getCorePoolSize();
// 最大线程数 // 最大线程数
@ -245,7 +235,6 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
int largestPoolSize = threadPoolExecutor.getLargestPoolSize(); int largestPoolSize = threadPoolExecutor.getLargestPoolSize();
// 线程池中执行任务总数量 (有锁) // 线程池中执行任务总数量 (有锁)
long completedTaskCount = threadPoolExecutor.getCompletedTaskCount(); long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
request.setActive(active.toUpperCase()); request.setActive(active.toUpperCase());
request.setIdentify(IdentifyUtil.getIdentify()); request.setIdentify(IdentifyUtil.getIdentify());
request.setCorePoolSize(corePoolSize); request.setCorePoolSize(corePoolSize);
@ -254,7 +243,6 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
request.setActiveCount(activeCount); request.setActiveCount(activeCount);
request.setLargestPoolSize(largestPoolSize); request.setLargestPoolSize(largestPoolSize);
request.setCompletedTaskCount(completedTaskCount); request.setCompletedTaskCount(completedTaskCount);
BlockingQueue<Runnable> queue = threadPoolExecutor.getQueue(); BlockingQueue<Runnable> queue = threadPoolExecutor.getQueue();
// 队列元素个数 // 队列元素个数
int queueSize = queue.size(); int queueSize = queue.size();
@ -268,18 +256,14 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner
request.setCapacity(queueCapacity); request.setCapacity(queueCapacity);
request.setQueueSize(queueSize); request.setQueueSize(queueSize);
request.setRemainingCapacity(remainingCapacity); request.setRemainingCapacity(remainingCapacity);
RejectedExecutionHandler rejectedExecutionHandler = threadPoolExecutor instanceof DynamicThreadPoolExecutor RejectedExecutionHandler rejectedExecutionHandler = threadPoolExecutor instanceof DynamicThreadPoolExecutor
? ((DynamicThreadPoolExecutor) threadPoolExecutor).getRedundancyHandler() ? ((DynamicThreadPoolExecutor) threadPoolExecutor).getRedundancyHandler()
: threadPoolExecutor.getRejectedExecutionHandler(); : threadPoolExecutor.getRejectedExecutionHandler();
request.setRejectedExecutionHandlerName(rejectedExecutionHandler.getClass().getSimpleName()); request.setRejectedExecutionHandlerName(rejectedExecutionHandler.getClass().getSimpleName());
long rejectCount = threadPoolExecutor instanceof DynamicThreadPoolExecutor long rejectCount = threadPoolExecutor instanceof DynamicThreadPoolExecutor
? ((DynamicThreadPoolExecutor) threadPoolExecutor).getRejectCountNum() ? ((DynamicThreadPoolExecutor) threadPoolExecutor).getRejectCountNum()
: -1L; : -1L;
request.setRejectCountNum(rejectCount); request.setRejectCountNum(rejectCount);
return request; return request;
} }
} }

@ -54,5 +54,4 @@ public class GlobalNotifyAlarmManage {
public static void put(String key, ThreadPoolNotifyAlarm val) { public static void put(String key, ThreadPoolNotifyAlarm val) {
NOTIFY_ALARM_MAP.put(key, val); NOTIFY_ALARM_MAP.put(key, val);
} }
} }

@ -113,5 +113,4 @@ public class GlobalThreadPoolManage {
public static Integer getThreadPoolNum() { public static Integer getThreadPoolNum() {
return listThreadPoolId().size(); return listThreadPoolId().size();
} }
} }

@ -83,7 +83,6 @@ public abstract class AbstractThreadPoolRuntime {
String currentLoad = CalculateUtil.divide(activeCount, maximumPoolSize) + ""; String currentLoad = CalculateUtil.divide(activeCount, maximumPoolSize) + "";
// 峰值负载 // 峰值负载
String peakLoad = CalculateUtil.divide(largestPoolSize, maximumPoolSize) + ""; String peakLoad = CalculateUtil.divide(largestPoolSize, maximumPoolSize) + "";
BlockingQueue<Runnable> queue = pool.getQueue(); BlockingQueue<Runnable> queue = pool.getQueue();
// 队列元素个数 // 队列元素个数
int queueSize = queue.size(); int queueSize = queue.size();
@ -93,7 +92,6 @@ public abstract class AbstractThreadPoolRuntime {
int remainingCapacity = queue.remainingCapacity(); int remainingCapacity = queue.remainingCapacity();
// 队列容量 // 队列容量
int queueCapacity = queueSize + remainingCapacity; int queueCapacity = queueSize + remainingCapacity;
stateInfo.setCoreSize(corePoolSize); stateInfo.setCoreSize(corePoolSize);
stateInfo.setTpId(threadPoolId); stateInfo.setTpId(threadPoolId);
stateInfo.setPoolSize(poolSize); stateInfo.setPoolSize(poolSize);
@ -107,7 +105,6 @@ public abstract class AbstractThreadPoolRuntime {
stateInfo.setQueueRemainingCapacity(remainingCapacity); stateInfo.setQueueRemainingCapacity(remainingCapacity);
stateInfo.setLargestPoolSize(largestPoolSize); stateInfo.setLargestPoolSize(largestPoolSize);
stateInfo.setCompletedTaskCount(completedTaskCount); stateInfo.setCompletedTaskCount(completedTaskCount);
long rejectCount = long rejectCount =
pool instanceof DynamicThreadPoolExecutor ? ((DynamicThreadPoolExecutor) pool).getRejectCountNum() : -1L; pool instanceof DynamicThreadPoolExecutor ? ((DynamicThreadPoolExecutor) pool).getRejectCountNum() : -1L;
stateInfo.setRejectCount(rejectCount); stateInfo.setRejectCount(rejectCount);
@ -115,5 +112,4 @@ public abstract class AbstractThreadPoolRuntime {
stateInfo.setTimestamp(System.currentTimeMillis()); stateInfo.setTimestamp(System.currentTimeMillis());
return supplement(stateInfo); return supplement(stateInfo);
} }
} }

@ -59,19 +59,15 @@ public class ThreadPoolRunStateHandler extends AbstractThreadPoolRuntime {
ByteConvertUtil.getPrintSize(runtimeInfo.getTotalMemory()), ByteConvertUtil.getPrintSize(runtimeInfo.getTotalMemory()),
" / 最大可用: ", " / 最大可用: ",
ByteConvertUtil.getPrintSize(runtimeInfo.getMaxMemory())).toString(); ByteConvertUtil.getPrintSize(runtimeInfo.getMaxMemory())).toString();
poolRunStateInfo.setCurrentLoad(poolRunStateInfo.getCurrentLoad() + "%"); poolRunStateInfo.setCurrentLoad(poolRunStateInfo.getCurrentLoad() + "%");
poolRunStateInfo.setPeakLoad(poolRunStateInfo.getPeakLoad() + "%"); poolRunStateInfo.setPeakLoad(poolRunStateInfo.getPeakLoad() + "%");
String ipAddress = hippo4JInetUtils.findFirstNonLoopbackHostInfo().getIpAddress(); String ipAddress = hippo4JInetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
poolRunStateInfo.setHost(ipAddress); poolRunStateInfo.setHost(ipAddress);
poolRunStateInfo.setMemoryProportion(memoryProportion); poolRunStateInfo.setMemoryProportion(memoryProportion);
poolRunStateInfo.setFreeMemory(ByteConvertUtil.getPrintSize(runtimeInfo.getFreeMemory())); poolRunStateInfo.setFreeMemory(ByteConvertUtil.getPrintSize(runtimeInfo.getFreeMemory()));
String threadPoolId = poolRunStateInfo.getTpId(); String threadPoolId = poolRunStateInfo.getTpId();
DynamicThreadPoolWrapper executorService = GlobalThreadPoolManage.getExecutorService(threadPoolId); DynamicThreadPoolWrapper executorService = GlobalThreadPoolManage.getExecutorService(threadPoolId);
ThreadPoolExecutor pool = executorService.getExecutor(); ThreadPoolExecutor pool = executorService.getExecutor();
String rejectedName; String rejectedName;
if (pool instanceof AbstractDynamicExecutorSupport) { if (pool instanceof AbstractDynamicExecutorSupport) {
rejectedName = ((DynamicThreadPoolExecutor) pool).getRedundancyHandler().getClass().getSimpleName(); rejectedName = ((DynamicThreadPoolExecutor) pool).getRedundancyHandler().getClass().getSimpleName();
@ -79,17 +75,12 @@ public class ThreadPoolRunStateHandler extends AbstractThreadPoolRuntime {
rejectedName = pool.getRejectedExecutionHandler().getClass().getSimpleName(); rejectedName = pool.getRejectedExecutionHandler().getClass().getSimpleName();
} }
poolRunStateInfo.setRejectedName(rejectedName); poolRunStateInfo.setRejectedName(rejectedName);
ManyPoolRunStateInfo manyPoolRunStateInfo = BeanUtil.toBean(poolRunStateInfo, ManyPoolRunStateInfo.class); ManyPoolRunStateInfo manyPoolRunStateInfo = BeanUtil.toBean(poolRunStateInfo, ManyPoolRunStateInfo.class);
manyPoolRunStateInfo.setIdentify(CLIENT_IDENTIFICATION_VALUE); manyPoolRunStateInfo.setIdentify(CLIENT_IDENTIFICATION_VALUE);
String active = environment.getProperty("spring.profiles.active", "UNKNOWN"); String active = environment.getProperty("spring.profiles.active", "UNKNOWN");
manyPoolRunStateInfo.setActive(active.toUpperCase()); manyPoolRunStateInfo.setActive(active.toUpperCase());
String threadPoolState = ThreadPoolStatusHandler.getThreadPoolState(pool); String threadPoolState = ThreadPoolStatusHandler.getThreadPoolState(pool);
manyPoolRunStateInfo.setState(threadPoolState); manyPoolRunStateInfo.setState(threadPoolState);
return manyPoolRunStateInfo; return manyPoolRunStateInfo;
} }
} }

@ -53,14 +53,12 @@ public class ThreadPoolStatusHandler {
try { try {
Method runStateLessThan = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateLessThan"); Method runStateLessThan = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateLessThan");
cn.hippo4j.common.toolkit.ReflectUtil.setAccessible(runStateLessThan); cn.hippo4j.common.toolkit.ReflectUtil.setAccessible(runStateLessThan);
AtomicInteger ctl = (AtomicInteger) ReflectUtil.getFieldValue(executor, "ctl"); AtomicInteger ctl = (AtomicInteger) ReflectUtil.getFieldValue(executor, "ctl");
int shutdown = (int) ReflectUtil.getFieldValue(executor, "SHUTDOWN"); int shutdown = (int) ReflectUtil.getFieldValue(executor, "SHUTDOWN");
boolean runStateLessThanBool = ReflectUtil.invoke(executor, runStateLessThan, ctl.get(), shutdown); boolean runStateLessThanBool = ReflectUtil.invoke(executor, runStateLessThan, ctl.get(), shutdown);
if (runStateLessThanBool) { if (runStateLessThanBool) {
return RUNNING; return RUNNING;
} }
Method runStateAtLeast = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateAtLeast"); Method runStateAtLeast = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateAtLeast");
cn.hippo4j.common.toolkit.ReflectUtil.setAccessible(runStateAtLeast); cn.hippo4j.common.toolkit.ReflectUtil.setAccessible(runStateAtLeast);
int terminated = (int) ReflectUtil.getFieldValue(executor, "TERMINATED"); int terminated = (int) ReflectUtil.getFieldValue(executor, "TERMINATED");
@ -68,12 +66,9 @@ public class ThreadPoolStatusHandler {
return resultStatus; return resultStatus;
} catch (Exception ex) { } catch (Exception ex) {
log.error("Failed to get thread pool status.", ex); log.error("Failed to get thread pool status.", ex);
EXCEPTION_FLAG.set(Boolean.FALSE); EXCEPTION_FLAG.set(Boolean.FALSE);
} }
} }
return "UNKNOWN"; return "UNKNOWN";
} }
} }

@ -77,7 +77,6 @@ public class AbstractBuildThreadPoolTemplate {
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
throw new IllegalArgumentException("Error creating thread pool parameter.", ex); throw new IllegalArgumentException("Error creating thread pool parameter.", ex);
} }
executorService.allowCoreThreadTimeOut(initParam.allowCoreThreadTimeOut); executorService.allowCoreThreadTimeOut(initParam.allowCoreThreadTimeOut);
return executorService; return executorService;
} }
@ -111,7 +110,6 @@ public class AbstractBuildThreadPoolTemplate {
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
throw new IllegalArgumentException("Error creating thread pool parameter.", ex); throw new IllegalArgumentException("Error creating thread pool parameter.", ex);
} }
taskQueue.setExecutor(fastThreadPoolExecutor); taskQueue.setExecutor(fastThreadPoolExecutor);
fastThreadPoolExecutor.allowCoreThreadTimeOut(initParam.allowCoreThreadTimeOut); fastThreadPoolExecutor.allowCoreThreadTimeOut(initParam.allowCoreThreadTimeOut);
return fastThreadPoolExecutor; return fastThreadPoolExecutor;
@ -142,7 +140,6 @@ public class AbstractBuildThreadPoolTemplate {
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
throw new IllegalArgumentException(String.format("Error creating thread pool parameter. threadPool id :: %s", initParam.getThreadPoolId()), ex); throw new IllegalArgumentException(String.format("Error creating thread pool parameter. threadPool id :: %s", initParam.getThreadPoolId()), ex);
} }
dynamicThreadPoolExecutor.setTaskDecorator(initParam.getTaskDecorator()); dynamicThreadPoolExecutor.setTaskDecorator(initParam.getTaskDecorator());
dynamicThreadPoolExecutor.allowCoreThreadTimeOut(initParam.allowCoreThreadTimeOut); dynamicThreadPoolExecutor.allowCoreThreadTimeOut(initParam.allowCoreThreadTimeOut);
return dynamicThreadPoolExecutor; return dynamicThreadPoolExecutor;

@ -169,5 +169,4 @@ public abstract class AbstractDynamicExecutorSupport extends ThreadPoolExecutor
} }
} }
} }
} }

@ -45,5 +45,4 @@ public class CommonDynamicThreadPool {
.build(); .build();
return poolExecutor; return poolExecutor;
} }
} }

@ -96,14 +96,12 @@ public enum QueueTypeEnum {
.filter(each -> Objects.equals(each.name, blockingQueueName)) .filter(each -> Objects.equals(each.name, blockingQueueName))
.findFirst() .findFirst()
.orElse(null); .orElse(null);
if (queueTypeEnum != null) { if (queueTypeEnum != null) {
blockingQueue = createBlockingQueue(queueTypeEnum.type, capacity); blockingQueue = createBlockingQueue(queueTypeEnum.type, capacity);
if (Objects.equals(blockingQueue.getClass().getSimpleName(), blockingQueueName)) { if (Objects.equals(blockingQueue.getClass().getSimpleName(), blockingQueueName)) {
return blockingQueue; return blockingQueue;
} }
} }
Collection<CustomBlockingQueue> customBlockingQueues = DynamicThreadPoolServiceLoader Collection<CustomBlockingQueue> customBlockingQueues = DynamicThreadPoolServiceLoader
.getSingletonServiceInstances(CustomBlockingQueue.class); .getSingletonServiceInstances(CustomBlockingQueue.class);
blockingQueue = Optional.ofNullable(blockingQueue) blockingQueue = Optional.ofNullable(blockingQueue)
@ -120,7 +118,6 @@ public enum QueueTypeEnum {
return new LinkedBlockingQueue(temCapacity); return new LinkedBlockingQueue(temCapacity);
})); }));
return blockingQueue; return blockingQueue;
} }
@ -148,7 +145,6 @@ public enum QueueTypeEnum {
} else if (Objects.equals(type, RESIZABLE_LINKED_BLOCKING_QUEUE.type)) { } else if (Objects.equals(type, RESIZABLE_LINKED_BLOCKING_QUEUE.type)) {
blockingQueue = new ResizableCapacityLinkedBlockIngQueue(capacity); blockingQueue = new ResizableCapacityLinkedBlockIngQueue(capacity);
} }
Collection<CustomBlockingQueue> customBlockingQueues = DynamicThreadPoolServiceLoader Collection<CustomBlockingQueue> customBlockingQueues = DynamicThreadPoolServiceLoader
.getSingletonServiceInstances(CustomBlockingQueue.class); .getSingletonServiceInstances(CustomBlockingQueue.class);
blockingQueue = Optional.ofNullable(blockingQueue).orElseGet(() -> customBlockingQueues.stream() blockingQueue = Optional.ofNullable(blockingQueue).orElseGet(() -> customBlockingQueues.stream()
@ -156,7 +152,6 @@ public enum QueueTypeEnum {
.map(each -> each.generateBlockingQueue()) .map(each -> each.generateBlockingQueue())
.findFirst() .findFirst()
.orElse(new LinkedBlockingQueue(capacity))); .orElse(new LinkedBlockingQueue(capacity)));
return blockingQueue; return blockingQueue;
} }
@ -170,8 +165,6 @@ public enum QueueTypeEnum {
Optional<QueueTypeEnum> queueTypeEnum = Arrays.stream(QueueTypeEnum.values()) Optional<QueueTypeEnum> queueTypeEnum = Arrays.stream(QueueTypeEnum.values())
.filter(each -> each.type == type) .filter(each -> each.type == type)
.findFirst(); .findFirst();
return queueTypeEnum.map(each -> each.name).orElse(""); return queueTypeEnum.map(each -> each.name).orElse("");
} }
} }

@ -52,7 +52,6 @@ public class RejectedPolicies {
executor.execute(r); executor.execute(r);
} }
} }
} }
/** /**
@ -71,7 +70,5 @@ public class RejectedPolicies {
log.error("Adding Queue task to thread pool failed.", e); log.error("Adding Queue task to thread pool failed.", e);
} }
} }
} }
} }

@ -101,18 +101,15 @@ public enum RejectedTypeEnum {
.filter(each -> Objects.equals(each.name, name)) .filter(each -> Objects.equals(each.name, name))
.findFirst() .findFirst()
.orElse(null); .orElse(null);
if (rejectedTypeEnum != null) { if (rejectedTypeEnum != null) {
return rejectedTypeEnum.rejectedHandler; return rejectedTypeEnum.rejectedHandler;
} }
Collection<CustomRejectedExecutionHandler> customRejectedExecutionHandlers = DynamicThreadPoolServiceLoader Collection<CustomRejectedExecutionHandler> customRejectedExecutionHandlers = DynamicThreadPoolServiceLoader
.getSingletonServiceInstances(CustomRejectedExecutionHandler.class); .getSingletonServiceInstances(CustomRejectedExecutionHandler.class);
Optional<RejectedExecutionHandler> customRejected = customRejectedExecutionHandlers.stream() Optional<RejectedExecutionHandler> customRejected = customRejectedExecutionHandlers.stream()
.filter(each -> Objects.equals(name, each.getName())) .filter(each -> Objects.equals(name, each.getName()))
.map(each -> each.generateRejected()) .map(each -> each.generateRejected())
.findFirst(); .findFirst();
return customRejected.orElse(ABORT_POLICY.rejectedHandler); return customRejected.orElse(ABORT_POLICY.rejectedHandler);
} }
@ -127,7 +124,6 @@ public enum RejectedTypeEnum {
.filter(each -> Objects.equals(type, each.type)) .filter(each -> Objects.equals(type, each.type))
.map(each -> each.rejectedHandler) .map(each -> each.rejectedHandler)
.findFirst(); .findFirst();
// 使用 SPI 匹配拒绝策略 // 使用 SPI 匹配拒绝策略
RejectedExecutionHandler resultRejected = rejectedTypeEnum.orElseGet(() -> { RejectedExecutionHandler resultRejected = rejectedTypeEnum.orElseGet(() -> {
Collection<CustomRejectedExecutionHandler> customRejectedExecutionHandlers = DynamicThreadPoolServiceLoader Collection<CustomRejectedExecutionHandler> customRejectedExecutionHandlers = DynamicThreadPoolServiceLoader
@ -136,10 +132,8 @@ public enum RejectedTypeEnum {
.filter(each -> Objects.equals(type, each.getType())) .filter(each -> Objects.equals(type, each.getType()))
.map(each -> each.generateRejected()) .map(each -> each.generateRejected())
.findFirst(); .findFirst();
return customRejected.orElse(ABORT_POLICY.rejectedHandler); return customRejected.orElse(ABORT_POLICY.rejectedHandler);
}); });
return resultRejected; return resultRejected;
} }
@ -152,5 +146,4 @@ public enum RejectedTypeEnum {
public static String getRejectedNameByType(int type) { public static String getRejectedNameByType(int type) {
return createPolicy(type).getClass().getSimpleName(); return createPolicy(type).getClass().getSimpleName();
} }
} }

@ -171,5 +171,4 @@ public class ThreadFactoryBuilder implements Builder<ThreadFactory> {
return thread; return thread;
}; };
} }
} }

@ -173,6 +173,14 @@ public class ThreadPoolBuilder implements Builder<ThreadPoolExecutor> {
return this; return this;
} }
public ThreadPoolBuilder singlePool(String threadNamePrefix) {
int singleNum = 1;
this.corePoolSize = singleNum;
this.maxPoolSize = singleNum;
this.threadNamePrefix = threadNamePrefix;
return this;
}
public ThreadPoolBuilder poolThreadSize(int corePoolSize, int maxPoolSize) { public ThreadPoolBuilder poolThreadSize(int corePoolSize, int maxPoolSize) {
this.corePoolSize = corePoolSize; this.corePoolSize = corePoolSize;
this.maxPoolSize = maxPoolSize; this.maxPoolSize = maxPoolSize;

@ -79,5 +79,4 @@ public class ThreadPoolExecutorTemplate extends ThreadPoolExecutor {
} }
}; };
} }
} }

@ -60,7 +60,6 @@ public abstract class AbstractWebThreadPoolService implements WebThreadPoolServi
} }
} }
} }
return executor; return executor;
} }
@ -72,5 +71,4 @@ public abstract class AbstractWebThreadPoolService implements WebThreadPoolServi
// ignore. Adaptation unit test. // ignore. Adaptation unit test.
} }
} }
} }

@ -30,6 +30,8 @@ import org.springframework.boot.web.server.WebServer;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMITER;
/** /**
* @author : wh * @author : wh
* @date : 2022/2/28 16:55 * @date : 2022/2/28 16:55
@ -50,10 +52,8 @@ public class JettyWebThreadPoolHandler extends AbstractWebThreadPoolService {
QueuedThreadPool queuedThreadPool = (QueuedThreadPool) executor; QueuedThreadPool queuedThreadPool = (QueuedThreadPool) executor;
poolBaseInfo.setCoreSize(queuedThreadPool.getMinThreads()); poolBaseInfo.setCoreSize(queuedThreadPool.getMinThreads());
poolBaseInfo.setMaximumSize(queuedThreadPool.getMaxThreads()); poolBaseInfo.setMaximumSize(queuedThreadPool.getMaxThreads());
BlockingQueue jobs = (BlockingQueue) ReflectUtil.getFieldValue(queuedThreadPool, "_jobs"); BlockingQueue jobs = (BlockingQueue) ReflectUtil.getFieldValue(queuedThreadPool, "_jobs");
int queueCapacity = jobs.remainingCapacity() + jobs.size(); int queueCapacity = jobs.remainingCapacity() + jobs.size();
poolBaseInfo.setQueueCapacity(queueCapacity); poolBaseInfo.setQueueCapacity(queueCapacity);
poolBaseInfo.setQueueType(jobs.getClass().getSimpleName()); poolBaseInfo.setQueueType(jobs.getClass().getSimpleName());
poolBaseInfo.setKeepAliveTime((long) queuedThreadPool.getIdleTimeout()); poolBaseInfo.setKeepAliveTime((long) queuedThreadPool.getIdleTimeout());
@ -67,16 +67,13 @@ public class JettyWebThreadPoolHandler extends AbstractWebThreadPoolService {
try { try {
parameterInfo = new PoolParameterInfo(); parameterInfo = new PoolParameterInfo();
QueuedThreadPool jettyExecutor = (QueuedThreadPool) executor; QueuedThreadPool jettyExecutor = (QueuedThreadPool) executor;
int minThreads = jettyExecutor.getMinThreads(); int minThreads = jettyExecutor.getMinThreads();
int maxThreads = jettyExecutor.getMaxThreads(); int maxThreads = jettyExecutor.getMaxThreads();
parameterInfo.setCoreSize(minThreads); parameterInfo.setCoreSize(minThreads);
parameterInfo.setMaxSize(maxThreads); parameterInfo.setMaxSize(maxThreads);
} catch (Exception ex) { } catch (Exception ex) {
log.error("Failed to get the jetty thread pool parameter.", ex); log.error("Failed to get the jetty thread pool parameter.", ex);
} }
return parameterInfo; return parameterInfo;
} }
@ -89,25 +86,20 @@ public class JettyWebThreadPoolHandler extends AbstractWebThreadPoolService {
public void updateWebThreadPool(PoolParameterInfo poolParameterInfo) { public void updateWebThreadPool(PoolParameterInfo poolParameterInfo) {
try { try {
QueuedThreadPool jettyExecutor = (QueuedThreadPool) executor; QueuedThreadPool jettyExecutor = (QueuedThreadPool) executor;
int minThreads = jettyExecutor.getMinThreads(); int minThreads = jettyExecutor.getMinThreads();
int maxThreads = jettyExecutor.getMaxThreads(); int maxThreads = jettyExecutor.getMaxThreads();
Integer coreSize = poolParameterInfo.getCoreSize(); Integer coreSize = poolParameterInfo.getCoreSize();
Integer maxSize = poolParameterInfo.getMaxSize(); Integer maxSize = poolParameterInfo.getMaxSize();
jettyExecutor.setMinThreads(coreSize); jettyExecutor.setMinThreads(coreSize);
jettyExecutor.setMaxThreads(maxSize); jettyExecutor.setMaxThreads(maxSize);
log.info( log.info(
"[JETTY] Changed web thread pool. " + "[JETTY] Changed web thread pool. " +
"\n coreSize :: [{}]" + "\n coreSize :: [{}]" +
"\n maxSize :: [{}]", "\n maxSize :: [{}]",
String.format("%s => %s", minThreads, jettyExecutor.getMinThreads()), String.format(CHANGE_DELIMITER, minThreads, jettyExecutor.getMinThreads()),
String.format("%s => %s", maxThreads, jettyExecutor.getMaxThreads())); String.format(CHANGE_DELIMITER, maxThreads, jettyExecutor.getMaxThreads()));
} catch (Exception ex) { } catch (Exception ex) {
log.error("Failed to modify the jetty thread pool parameter.", ex); log.error("Failed to modify the jetty thread pool parameter.", ex);
} }
} }
} }

@ -30,6 +30,8 @@ import org.springframework.boot.web.server.WebServer;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMITER;
/** /**
* Tomcat web thread pool handler. * Tomcat web thread pool handler.
* *
@ -52,7 +54,6 @@ public class TomcatWebThreadPoolHandler extends AbstractWebThreadPoolService {
log.warn("Exception getting Tomcat thread pool. Exception message :: {}", EXCEPTION_MESSAGE); log.warn("Exception getting Tomcat thread pool. Exception message :: {}", EXCEPTION_MESSAGE);
return null; return null;
} }
Executor tomcatExecutor = null; Executor tomcatExecutor = null;
try { try {
tomcatExecutor = ((TomcatWebServer) webServer).getTomcat().getConnector().getProtocolHandler().getExecutor(); tomcatExecutor = ((TomcatWebServer) webServer).getTomcat().getConnector().getProtocolHandler().getExecutor();
@ -61,7 +62,6 @@ public class TomcatWebThreadPoolHandler extends AbstractWebThreadPoolService {
EXCEPTION_MESSAGE = ex.getMessage(); EXCEPTION_MESSAGE = ex.getMessage();
log.error("Failed to get Tomcat thread pool. Message :: {}", EXCEPTION_MESSAGE); log.error("Failed to get Tomcat thread pool. Message :: {}", EXCEPTION_MESSAGE);
} }
return tomcatExecutor; return tomcatExecutor;
} }
@ -85,7 +85,6 @@ public class TomcatWebThreadPoolHandler extends AbstractWebThreadPoolService {
poolBaseInfo.setQueueType(queue.getClass().getSimpleName()); poolBaseInfo.setQueueType(queue.getClass().getSimpleName());
poolBaseInfo.setQueueCapacity(queueCapacity); poolBaseInfo.setQueueCapacity(queueCapacity);
poolBaseInfo.setRejectedName(rejectedExecutionHandler.getClass().getSimpleName()); poolBaseInfo.setRejectedName(rejectedExecutionHandler.getClass().getSimpleName());
return poolBaseInfo; return poolBaseInfo;
} }
@ -105,7 +104,6 @@ public class TomcatWebThreadPoolHandler extends AbstractWebThreadPoolService {
} catch (Exception ex) { } catch (Exception ex) {
log.error("Failed to get the tomcat thread pool parameter.", ex); log.error("Failed to get the tomcat thread pool parameter.", ex);
} }
return parameterInfo; return parameterInfo;
} }
@ -121,7 +119,6 @@ public class TomcatWebThreadPoolHandler extends AbstractWebThreadPoolService {
int originalCoreSize = tomcatExecutor.getCorePoolSize(); int originalCoreSize = tomcatExecutor.getCorePoolSize();
int originalMaximumPoolSize = tomcatExecutor.getMaximumPoolSize(); int originalMaximumPoolSize = tomcatExecutor.getMaximumPoolSize();
long originalKeepAliveTime = tomcatExecutor.getKeepAliveTime(TimeUnit.SECONDS); long originalKeepAliveTime = tomcatExecutor.getKeepAliveTime(TimeUnit.SECONDS);
tomcatExecutor.setCorePoolSize(poolParameterInfo.getCoreSize()); tomcatExecutor.setCorePoolSize(poolParameterInfo.getCoreSize());
tomcatExecutor.setMaximumPoolSize(poolParameterInfo.getMaxSize()); tomcatExecutor.setMaximumPoolSize(poolParameterInfo.getMaxSize());
tomcatExecutor.setKeepAliveTime(poolParameterInfo.getKeepAliveTime(), TimeUnit.SECONDS); tomcatExecutor.setKeepAliveTime(poolParameterInfo.getKeepAliveTime(), TimeUnit.SECONDS);
@ -130,12 +127,11 @@ public class TomcatWebThreadPoolHandler extends AbstractWebThreadPoolService {
"\n coreSize :: [{}]" + "\n coreSize :: [{}]" +
"\n maxSize :: [{}]" + "\n maxSize :: [{}]" +
"\n keepAliveTime :: [{}]", "\n keepAliveTime :: [{}]",
String.format("%s => %s", originalCoreSize, poolParameterInfo.getCoreSize()), String.format(CHANGE_DELIMITER, originalCoreSize, poolParameterInfo.getCoreSize()),
String.format("%s => %s", originalMaximumPoolSize, poolParameterInfo.getMaxSize()), String.format(CHANGE_DELIMITER, originalMaximumPoolSize, poolParameterInfo.getMaxSize()),
String.format("%s => %s", originalKeepAliveTime, poolParameterInfo.getKeepAliveTime())); String.format(CHANGE_DELIMITER, originalKeepAliveTime, poolParameterInfo.getKeepAliveTime()));
} catch (Exception ex) { } catch (Exception ex) {
log.error("Failed to modify the Tomcat thread pool parameter.", ex); log.error("Failed to modify the Tomcat thread pool parameter.", ex);
} }
} }
} }

@ -38,6 +38,8 @@ import java.util.Date;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMITER;
/** /**
* Undertow web thread pool handler. * Undertow web thread pool handler.
* *
@ -77,7 +79,6 @@ public class UndertowWebThreadPoolHandler extends AbstractWebThreadPoolService {
} catch (Exception ex) { } catch (Exception ex) {
log.error("The undertow container failed to get thread pool parameters.", ex); log.error("The undertow container failed to get thread pool parameters.", ex);
} }
return poolBaseInfo; return poolBaseInfo;
} }
@ -97,7 +98,6 @@ public class UndertowWebThreadPoolHandler extends AbstractWebThreadPoolService {
} catch (Exception ex) { } catch (Exception ex) {
log.error("Failed to get the undertow thread pool parameter.", ex); log.error("Failed to get the undertow thread pool parameter.", ex);
} }
return parameterInfo; return parameterInfo;
} }
@ -106,7 +106,6 @@ public class UndertowWebThreadPoolHandler extends AbstractWebThreadPoolService {
PoolRunStateInfo stateInfo = new PoolRunStateInfo(); PoolRunStateInfo stateInfo = new PoolRunStateInfo();
XnioWorker xnioWorker = (XnioWorker) executor; XnioWorker xnioWorker = (XnioWorker) executor;
// private final TaskPool taskPool;
Field field = ReflectionUtils.findField(XnioWorker.class, "taskPool"); Field field = ReflectionUtils.findField(XnioWorker.class, "taskPool");
ReflectionUtils.makeAccessible(field); ReflectionUtils.makeAccessible(field);
Object fieldObject = ReflectionUtils.getField(field, xnioWorker); Object fieldObject = ReflectionUtils.getField(field, xnioWorker);
@ -153,15 +152,12 @@ public class UndertowWebThreadPoolHandler extends AbstractWebThreadPoolService {
public void updateWebThreadPool(PoolParameterInfo poolParameterInfo) { public void updateWebThreadPool(PoolParameterInfo poolParameterInfo) {
try { try {
XnioWorker xnioWorker = (XnioWorker) executor; XnioWorker xnioWorker = (XnioWorker) executor;
Integer coreSize = poolParameterInfo.getCoreSize(); Integer coreSize = poolParameterInfo.getCoreSize();
Integer maxSize = poolParameterInfo.getMaxSize(); Integer maxSize = poolParameterInfo.getMaxSize();
Integer keepAliveTime = poolParameterInfo.getKeepAliveTime(); Integer keepAliveTime = poolParameterInfo.getKeepAliveTime();
int originalCoreSize = xnioWorker.getOption(Options.WORKER_TASK_CORE_THREADS); int originalCoreSize = xnioWorker.getOption(Options.WORKER_TASK_CORE_THREADS);
int originalMaximumPoolSize = xnioWorker.getOption(Options.WORKER_TASK_MAX_THREADS); int originalMaximumPoolSize = xnioWorker.getOption(Options.WORKER_TASK_MAX_THREADS);
int originalKeepAliveTime = xnioWorker.getOption(Options.WORKER_TASK_KEEPALIVE); int originalKeepAliveTime = xnioWorker.getOption(Options.WORKER_TASK_KEEPALIVE);
xnioWorker.setOption(Options.WORKER_TASK_CORE_THREADS, coreSize); xnioWorker.setOption(Options.WORKER_TASK_CORE_THREADS, coreSize);
xnioWorker.setOption(Options.WORKER_TASK_MAX_THREADS, maxSize); xnioWorker.setOption(Options.WORKER_TASK_MAX_THREADS, maxSize);
xnioWorker.setOption(Options.WORKER_TASK_KEEPALIVE, keepAliveTime); xnioWorker.setOption(Options.WORKER_TASK_KEEPALIVE, keepAliveTime);
@ -170,13 +166,11 @@ public class UndertowWebThreadPoolHandler extends AbstractWebThreadPoolService {
"\n coreSize :: [{}]" + "\n coreSize :: [{}]" +
"\n maxSize :: [{}]" + "\n maxSize :: [{}]" +
"\n keepAliveTime :: [{}]", "\n keepAliveTime :: [{}]",
String.format("%s => %s", originalCoreSize, coreSize), String.format(CHANGE_DELIMITER, originalCoreSize, coreSize),
String.format("%s => %s", originalMaximumPoolSize, maxSize), String.format(CHANGE_DELIMITER, originalMaximumPoolSize, maxSize),
String.format("%s => %s", originalKeepAliveTime, keepAliveTime)); String.format(CHANGE_DELIMITER, originalKeepAliveTime, keepAliveTime));
} catch (Exception ex) { } catch (Exception ex) {
log.error("Failed to modify the undertow thread pool parameter.", ex); log.error("Failed to modify the undertow thread pool parameter.", ex);
} }
} }
} }

@ -42,8 +42,6 @@ public class WebThreadPoolHandlerChoose {
} catch (Exception ex) { } catch (Exception ex) {
throw new ServiceException("Web thread pool service bean not found.", ex); throw new ServiceException("Web thread pool service bean not found.", ex);
} }
return webThreadPoolService; return webThreadPoolService;
} }
} }

@ -51,5 +51,4 @@ public class WebThreadPoolRunStateHandler extends AbstractThreadPoolRuntime {
return poolRunStateInfo; return poolRunStateInfo;
} }
} }

@ -66,5 +66,4 @@ public interface WebThreadPoolService {
* @param poolParameterInfo * @param poolParameterInfo
*/ */
void updateWebThreadPool(PoolParameterInfo poolParameterInfo); void updateWebThreadPool(PoolParameterInfo poolParameterInfo);
} }

@ -58,16 +58,13 @@ public class DynamicThreadPoolBannerHandler implements InitializingBean {
"| |) | || | ' \\/ _` | ' \\| / _| | | | _/\n" + "| |) | || | ' \\/ _` | ' \\| / _| | | | _/\n" +
"|___/ \\_, |_||_\\__,_|_|_|_|_\\__| |_| |_| \n" + "|___/ \\_, |_||_\\__,_|_|_|_|_\\__| |_| |_| \n" +
" |__/ \n"; " |__/ \n";
if (properties.getBanner()) { if (properties.getBanner()) {
String version = getVersion(); String version = getVersion();
version = (version != null) ? " (v" + version + ")" : "no version."; version = (version != null) ? " (v" + version + ")" : "no version.";
StringBuilder padding = new StringBuilder(); StringBuilder padding = new StringBuilder();
while (padding.length() < STRAP_LINE_SIZE - (version.length() + DYNAMIC_THREAD_POOL.length())) { while (padding.length() < STRAP_LINE_SIZE - (version.length() + DYNAMIC_THREAD_POOL.length())) {
padding.append(" "); padding.append(" ");
} }
System.out.println(AnsiOutput.toString(banner, AnsiColor.GREEN, DYNAMIC_THREAD_POOL, AnsiColor.DEFAULT, System.out.println(AnsiOutput.toString(banner, AnsiColor.GREEN, DYNAMIC_THREAD_POOL, AnsiColor.DEFAULT,
padding.toString(), AnsiStyle.FAINT, version, "\n\n", HIPPO4J_GITHUB, "\n", HIPPO4J_SITE, "\n")); padding.toString(), AnsiStyle.FAINT, version, "\n\n", HIPPO4J_GITHUB, "\n", HIPPO4J_SITE, "\n"));
@ -78,5 +75,4 @@ public class DynamicThreadPoolBannerHandler implements InitializingBean {
final Package pkg = DynamicThreadPoolBannerHandler.class.getPackage(); final Package pkg = DynamicThreadPoolBannerHandler.class.getPackage();
return pkg != null ? pkg.getImplementationVersion() : ""; return pkg != null ? pkg.getImplementationVersion() : "";
} }
} }

@ -44,17 +44,14 @@ public class RejectedProxyInvocationHandler implements InvocationHandler {
@Override @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
rejectCount.incrementAndGet(); rejectCount.incrementAndGet();
if (ApplicationContextHolder.getInstance() != null) { if (ApplicationContextHolder.getInstance() != null) {
ThreadPoolNotifyAlarmHandler alarmHandler = ApplicationContextHolder.getBean(ThreadPoolNotifyAlarmHandler.class); ThreadPoolNotifyAlarmHandler alarmHandler = ApplicationContextHolder.getBean(ThreadPoolNotifyAlarmHandler.class);
alarmHandler.checkPoolRejectedAlarm(threadPoolId); alarmHandler.checkPoolRejectedAlarm(threadPoolId);
} }
try { try {
return method.invoke(target, args); return method.invoke(target, args);
} catch (InvocationTargetException ex) { } catch (InvocationTargetException ex) {
throw ex.getCause(); throw ex.getCause();
} }
} }
} }

@ -43,8 +43,6 @@ public class RejectedProxyUtil {
rejectedExecutionHandler.getClass().getClassLoader(), rejectedExecutionHandler.getClass().getClassLoader(),
new Class[]{RejectedExecutionHandler.class}, new Class[]{RejectedExecutionHandler.class},
new RejectedProxyInvocationHandler(rejectedExecutionHandler, threadPoolId, rejectedNum)); new RejectedProxyInvocationHandler(rejectedExecutionHandler, threadPoolId, rejectedNum));
return rejectedProxy; return rejectedProxy;
} }
} }

@ -49,5 +49,4 @@ public interface CustomBlockingQueue {
* @return * @return
*/ */
BlockingQueue generateBlockingQueue(); BlockingQueue generateBlockingQueue();
} }

@ -49,5 +49,4 @@ public interface CustomRejectedExecutionHandler {
* @return * @return
*/ */
RejectedExecutionHandler generateRejected(); RejectedExecutionHandler generateRejected();
} }

@ -92,5 +92,4 @@ public class DynamicThreadPoolServiceLoader {
throw new ServiceLoaderInstantiationException(clazz, ex); throw new ServiceLoaderInstantiationException(clazz, ex);
} }
} }
} }

@ -28,5 +28,4 @@ public class ServiceLoaderInstantiationException extends RuntimeException {
public ServiceLoaderInstantiationException(final Class<?> clazz, final Exception cause) { public ServiceLoaderInstantiationException(final Class<?> clazz, final Exception cause) {
super(String.format("Can not find public default constructor for SPI class `%s`", clazz.getName()), cause); super(String.format("Can not find public default constructor for SPI class `%s`", clazz.getName()), cause);
} }
} }

@ -35,5 +35,4 @@ public class CalculateUtil {
public static int divide(int num1, int num2) { public static int divide(int num1, int num2) {
return ((int) (Double.parseDouble(num1 + "") / Double.parseDouble(num2 + "") * 100)); return ((int) (Double.parseDouble(num1 + "") / Double.parseDouble(num2 + "") * 100));
} }
} }

@ -61,7 +61,6 @@ public class IdentifyUtil {
port, port,
IDENTIFY_SLICER_SYMBOL, IDENTIFY_SLICER_SYMBOL,
CLIENT_IDENTIFICATION_VALUE).toString(); CLIENT_IDENTIFICATION_VALUE).toString();
IDENTIFY = identification; IDENTIFY = identification;
return identification; return identification;
} }
@ -76,15 +75,12 @@ public class IdentifyUtil {
while (StrUtil.isBlank(IDENTIFY)) { while (StrUtil.isBlank(IDENTIFY)) {
ConfigurableEnvironment environment = ApplicationContextHolder.getBean(ConfigurableEnvironment.class); ConfigurableEnvironment environment = ApplicationContextHolder.getBean(ConfigurableEnvironment.class);
InetUtils inetUtils = ApplicationContextHolder.getBean(InetUtils.class); InetUtils inetUtils = ApplicationContextHolder.getBean(InetUtils.class);
if (environment != null && inetUtils != null) { if (environment != null && inetUtils != null) {
String identify = generate(environment, inetUtils); String identify = generate(environment, inetUtils);
return identify; return identify;
} }
Thread.sleep(500); Thread.sleep(500);
} }
return IDENTIFY; return IDENTIFY;
} }
@ -99,8 +95,6 @@ public class IdentifyUtil {
public static String getThreadPoolIdentify(String threadPoolId, String itemId, String namespace) { public static String getThreadPoolIdentify(String threadPoolId, String itemId, String namespace) {
ArrayList<String> params = Lists.newArrayList( ArrayList<String> params = Lists.newArrayList(
threadPoolId, itemId, namespace, getIdentify()); threadPoolId, itemId, namespace, getIdentify());
return Joiner.on(GROUP_KEY_DELIMITER).join(params); return Joiner.on(GROUP_KEY_DELIMITER).join(params);
} }
} }

@ -53,5 +53,4 @@ public class TraceContextUtil {
public static void setExecuteTimeoutTraceKey(String key) { public static void setExecuteTimeoutTraceKey(String key) {
EXECUTE_TIMEOUT_TRACE_KEY = key; EXECUTE_TIMEOUT_TRACE_KEY = key;
} }
} }

@ -54,6 +54,9 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMITER;
import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_THREAD_POOL_TEXT;
/** /**
* Abstract core thread pool dynamic refresh. * Abstract core thread pool dynamic refresh.
* *
@ -68,10 +71,7 @@ public abstract class AbstractCoreThreadPoolDynamicRefresh implements ThreadPool
protected final BootstrapCoreProperties bootstrapCoreProperties; protected final BootstrapCoreProperties bootstrapCoreProperties;
protected final ExecutorService dynamicRefreshExecutorService = ThreadPoolBuilder.builder() protected final ExecutorService dynamicRefreshExecutorService = ThreadPoolBuilder.builder().singlePool("client.dynamic.refresh").build();
.threadFactory("client.dynamic.refresh")
.singlePool()
.build();
@Override @Override
public void dynamicRefresh(String content) { public void dynamicRefresh(String content) {
@ -176,26 +176,16 @@ public abstract class AbstractCoreThreadPoolDynamicRefresh implements ThreadPool
ExecutorProperties beforeProperties = GlobalCoreThreadPoolManage.getProperties(properties.getThreadPoolId()); ExecutorProperties beforeProperties = GlobalCoreThreadPoolManage.getProperties(properties.getThreadPoolId());
// refresh executor properties // refresh executor properties
GlobalCoreThreadPoolManage.refresh(threadPoolId, properties); GlobalCoreThreadPoolManage.refresh(threadPoolId, properties);
log.info( log.info(CHANGE_THREAD_POOL_TEXT,
"[{}] Changed thread pool. " +
"\n coreSize :: [{}]" +
"\n maxSize :: [{}]" +
"\n queueType :: [{}]" +
"\n capacity :: [{}]" +
"\n keepAliveTime :: [{}]" +
"\n executeTimeOut :: [{}]" +
"\n rejectedType :: [{}]" +
"\n allowCoreThreadTimeOut :: [{}]",
threadPoolId.toUpperCase(), threadPoolId.toUpperCase(),
String.format("%s => %s", beforeProperties.getCorePoolSize(), properties.getCorePoolSize()), String.format(CHANGE_DELIMITER, beforeProperties.getCorePoolSize(), properties.getCorePoolSize()),
String.format("%s => %s", beforeProperties.getMaximumPoolSize(), properties.getMaximumPoolSize()), String.format(CHANGE_DELIMITER, beforeProperties.getMaximumPoolSize(), properties.getMaximumPoolSize()),
String.format("%s => %s", beforeProperties.getBlockingQueue(), properties.getBlockingQueue()), String.format(CHANGE_DELIMITER, beforeProperties.getBlockingQueue(), properties.getBlockingQueue()),
String.format("%s => %s", beforeProperties.getQueueCapacity(), properties.getQueueCapacity()), String.format(CHANGE_DELIMITER, beforeProperties.getQueueCapacity(), properties.getQueueCapacity()),
String.format("%s => %s", beforeProperties.getKeepAliveTime(), properties.getKeepAliveTime()), String.format(CHANGE_DELIMITER, beforeProperties.getKeepAliveTime(), properties.getKeepAliveTime()),
String.format("%s => %s", beforeProperties.getExecuteTimeOut(), properties.getExecuteTimeOut()), String.format(CHANGE_DELIMITER, beforeProperties.getExecuteTimeOut(), properties.getExecuteTimeOut()),
String.format("%s => %s", beforeProperties.getRejectedHandler(), properties.getRejectedHandler()), String.format(CHANGE_DELIMITER, beforeProperties.getRejectedHandler(), properties.getRejectedHandler()),
String.format("%s => %s", beforeProperties.getAllowCoreThreadTimeOut(), properties.getAllowCoreThreadTimeOut())); String.format(CHANGE_DELIMITER, beforeProperties.getAllowCoreThreadTimeOut(), properties.getAllowCoreThreadTimeOut()));
try { try {
threadPoolNotifyAlarmHandler.sendPoolConfigChange(newChangeRequest(beforeProperties, properties)); threadPoolNotifyAlarmHandler.sendPoolConfigChange(newChangeRequest(beforeProperties, properties));
} catch (Throwable ex) { } catch (Throwable ex) {
@ -241,7 +231,6 @@ public abstract class AbstractCoreThreadPoolDynamicRefresh implements ThreadPool
private boolean checkConsistency(String threadPoolId, ExecutorProperties properties) { private boolean checkConsistency(String threadPoolId, ExecutorProperties properties) {
ExecutorProperties beforeProperties = GlobalCoreThreadPoolManage.getProperties(properties.getThreadPoolId()); ExecutorProperties beforeProperties = GlobalCoreThreadPoolManage.getProperties(properties.getThreadPoolId());
ThreadPoolExecutor executor = GlobalThreadPoolManage.getExecutorService(threadPoolId).getExecutor(); ThreadPoolExecutor executor = GlobalThreadPoolManage.getExecutorService(threadPoolId).getExecutor();
boolean result = !Objects.equals(beforeProperties.getCorePoolSize(), properties.getCorePoolSize()) boolean result = !Objects.equals(beforeProperties.getCorePoolSize(), properties.getCorePoolSize())
|| !Objects.equals(beforeProperties.getMaximumPoolSize(), properties.getMaximumPoolSize()) || !Objects.equals(beforeProperties.getMaximumPoolSize(), properties.getMaximumPoolSize())
|| !Objects.equals(beforeProperties.getAllowCoreThreadTimeOut(), properties.getAllowCoreThreadTimeOut()) || !Objects.equals(beforeProperties.getAllowCoreThreadTimeOut(), properties.getAllowCoreThreadTimeOut())

@ -62,5 +62,4 @@ public class ApolloRefresherHandler extends AbstractCoreThreadPoolDynamicRefresh
config.addChangeListener(configChangeListener); config.addChangeListener(configChangeListener);
log.info("dynamic-thread-pool refresher, add apollo listener success, namespace: {}", namespace); log.info("dynamic-thread-pool refresher, add apollo listener success, namespace: {}", namespace);
} }
} }

@ -66,7 +66,6 @@ public class BootstrapCorePropertiesBinderAdapt {
bindableCoreProperties = adapt(configInfo); bindableCoreProperties = adapt(configInfo);
} }
} }
return bindableCoreProperties; return bindableCoreProperties;
} }
@ -86,14 +85,13 @@ public class BootstrapCorePropertiesBinderAdapt {
boolean containFlag = key != null boolean containFlag = key != null
&& StringUtil.isNotBlank((String) key) && StringUtil.isNotBlank((String) key)
&& (((String) key).indexOf(PREFIX + ".executors") != -1 && (((String) key).indexOf(PREFIX + ".executors") != -1
|| ((String) key).indexOf(PREFIX + ".notify-platforms") != -1 || ((String) key).indexOf(PREFIX + ".notify-platforms") != -1
|| ((String) key).indexOf(PREFIX + ".notifyPlatforms") != -1); || ((String) key).indexOf(PREFIX + ".notifyPlatforms") != -1);
if (containFlag) { if (containFlag) {
String targetKey = key.toString().replace(PREFIX + ".", ""); String targetKey = key.toString().replace(PREFIX + ".", "");
targetMap.put(targetKey, val); targetMap.put(targetKey, val);
} }
}); });
// convert // convert
List<ExecutorProperties> executorPropertiesList = Lists.newArrayList(); List<ExecutorProperties> executorPropertiesList = Lists.newArrayList();
List<NotifyPlatformProperties> notifyPropertiesList = Lists.newArrayList(); List<NotifyPlatformProperties> notifyPropertiesList = Lists.newArrayList();
@ -111,7 +109,6 @@ public class BootstrapCorePropertiesBinderAdapt {
if (notifyKeySplit != null && notifyKeySplit.length > 0) { if (notifyKeySplit != null && notifyKeySplit.length > 0) {
key = key.replace("-", "_"); key = key.replace("-", "_");
} }
notifySingleMap.put(key, entry.getValue()); notifySingleMap.put(key, entry.getValue());
} else { } else {
key = key.replace("executors[" + i + "].", ""); key = key.replace("executors[" + i + "].", "");
@ -123,27 +120,22 @@ public class BootstrapCorePropertiesBinderAdapt {
executorSingleMap.put(key, entry.getValue()); executorSingleMap.put(key, entry.getValue());
} }
} }
if (key.indexOf("notify-platforms[" + i + "].") != -1 || key.indexOf("notifyPlatforms[" + i + "].") != -1) { if (key.indexOf("notify-platforms[" + i + "].") != -1 || key.indexOf("notifyPlatforms[" + i + "].") != -1) {
if (key.indexOf("notify-platforms[" + i + "].") != -1) { if (key.indexOf("notify-platforms[" + i + "].") != -1) {
key = key.replace("notify-platforms[" + i + "].", ""); key = key.replace("notify-platforms[" + i + "].", "");
} else { } else {
key = key.replace("notifyPlatforms[" + i + "].", ""); key = key.replace("notifyPlatforms[" + i + "].", "");
} }
String[] keySplit = key.split("-"); String[] keySplit = key.split("-");
if (keySplit != null && keySplit.length > 0) { if (keySplit != null && keySplit.length > 0) {
key = key.replace("-", "_"); key = key.replace("-", "_");
} }
platformSingleMap.put(key, entry.getValue()); platformSingleMap.put(key, entry.getValue());
} }
} }
if (CollectionUtil.isEmpty(executorSingleMap) && CollectionUtil.isEmpty(platformSingleMap)) { if (CollectionUtil.isEmpty(executorSingleMap) && CollectionUtil.isEmpty(platformSingleMap)) {
break; break;
} }
if (CollectionUtil.isNotEmpty(executorSingleMap)) { if (CollectionUtil.isNotEmpty(executorSingleMap)) {
ExecutorProperties executorProperties = BeanUtil.mapToBean(executorSingleMap, ExecutorProperties.class, true, CopyOptions.create()); ExecutorProperties executorProperties = BeanUtil.mapToBean(executorSingleMap, ExecutorProperties.class, true, CopyOptions.create());
if (executorProperties != null) { if (executorProperties != null) {
@ -156,15 +148,12 @@ public class BootstrapCorePropertiesBinderAdapt {
notifyReceivesMap.put(value.name(), (String) receives); notifyReceivesMap.put(value.name(), (String) receives);
} }
} }
alarm.setReceives(notifyReceivesMap); alarm.setReceives(notifyReceivesMap);
executorProperties.setNotify(alarm); executorProperties.setNotify(alarm);
} }
executorPropertiesList.add(executorProperties); executorPropertiesList.add(executorProperties);
} }
} }
if (CollectionUtil.isNotEmpty(platformSingleMap)) { if (CollectionUtil.isNotEmpty(platformSingleMap)) {
NotifyPlatformProperties notifyPlatformProperties = BeanUtil.mapToBean(platformSingleMap, NotifyPlatformProperties.class, true, CopyOptions.create()); NotifyPlatformProperties notifyPlatformProperties = BeanUtil.mapToBean(platformSingleMap, NotifyPlatformProperties.class, true, CopyOptions.create());
if (notifyPlatformProperties != null) { if (notifyPlatformProperties != null) {
@ -172,15 +161,12 @@ public class BootstrapCorePropertiesBinderAdapt {
} }
} }
} }
bindableCoreProperties = new BootstrapCoreProperties(); bindableCoreProperties = new BootstrapCoreProperties();
bindableCoreProperties.setExecutors(executorPropertiesList); bindableCoreProperties.setExecutors(executorPropertiesList);
bindableCoreProperties.setNotifyPlatforms(notifyPropertiesList); bindableCoreProperties.setNotifyPlatforms(notifyPropertiesList);
} catch (Exception ex) { } catch (Exception ex) {
throw ex; throw ex;
} }
return bindableCoreProperties; return bindableCoreProperties;
} }
} }

@ -61,5 +61,4 @@ public class NacosCloudRefresherHandler extends AbstractCoreThreadPoolDynamicRef
} }
}); });
} }
} }

@ -61,5 +61,4 @@ public class NacosRefresherHandler extends AbstractCoreThreadPoolDynamicRefresh
} }
}); });
} }
} }

@ -112,5 +112,4 @@ public class ZookeeperRefresherHandler extends AbstractCoreThreadPoolDynamicRefr
log.error("load zk node error, nodePath is {}", nodePath, e); log.error("load zk node error, nodePath is {}", nodePath, e);
} }
} }
} }

@ -40,6 +40,9 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_DELIMITER;
import static cn.hippo4j.common.constant.ChangeThreadPoolConstants.CHANGE_THREAD_POOL_TEXT;
/** /**
* Thread pool dynamic refresh. * Thread pool dynamic refresh.
* *
@ -110,26 +113,17 @@ public class ServerThreadPoolDynamicRefresh implements ThreadPoolDynamicRefresh
request.setNowExecuteTimeOut(originalExecuteTimeOut); request.setNowExecuteTimeOut(originalExecuteTimeOut);
threadPoolNotifyAlarmHandler.sendPoolConfigChange(request); threadPoolNotifyAlarmHandler.sendPoolConfigChange(request);
log.info( log.info(CHANGE_THREAD_POOL_TEXT,
"[{}] Changed thread pool. " +
"\n coreSize :: [{}]" +
"\n maxSize :: [{}]" +
"\n queueType :: [{}]" +
"\n capacity :: [{}]" +
"\n keepAliveTime :: [{}]" +
"\n executeTimeOut :: [{}]" +
"\n rejectedType :: [{}]" +
"\n allowCoreThreadTimeOut :: [{}]",
threadPoolId.toUpperCase(), threadPoolId.toUpperCase(),
String.format("%s => %s", originalCoreSize, afterExecutor.getCorePoolSize()), String.format(CHANGE_DELIMITER, originalCoreSize, afterExecutor.getCorePoolSize()),
String.format("%s => %s", originalMaximumPoolSize, afterExecutor.getMaximumPoolSize()), String.format(CHANGE_DELIMITER, originalMaximumPoolSize, afterExecutor.getMaximumPoolSize()),
String.format("%s => %s", originalQuery, QueueTypeEnum.getBlockingQueueNameByType(parameter.getQueueType())), String.format(CHANGE_DELIMITER, originalQuery, QueueTypeEnum.getBlockingQueueNameByType(parameter.getQueueType())),
String.format("%s => %s", originalCapacity, String.format(CHANGE_DELIMITER, originalCapacity,
(afterExecutor.getQueue().remainingCapacity() + afterExecutor.getQueue().size())), (afterExecutor.getQueue().remainingCapacity() + afterExecutor.getQueue().size())),
String.format("%s => %s", originalKeepAliveTime, afterExecutor.getKeepAliveTime(TimeUnit.SECONDS)), String.format(CHANGE_DELIMITER, originalKeepAliveTime, afterExecutor.getKeepAliveTime(TimeUnit.SECONDS)),
String.format("%s => %s", originalExecuteTimeOut, originalExecuteTimeOut), String.format(CHANGE_DELIMITER, originalExecuteTimeOut, originalExecuteTimeOut),
String.format("%s => %s", originalRejected, RejectedTypeEnum.getRejectedNameByType(parameter.getRejectedType())), String.format(CHANGE_DELIMITER, originalRejected, RejectedTypeEnum.getRejectedNameByType(parameter.getRejectedType())),
String.format("%s => %s", originalAllowCoreThreadTimeOut, EnableEnum.getBool(parameter.getAllowCoreThreadTimeOut()))); String.format(CHANGE_DELIMITER, originalAllowCoreThreadTimeOut, EnableEnum.getBool(parameter.getAllowCoreThreadTimeOut())));
} }
/** /**

Loading…
Cancel
Save