获取线程池运行状态. (#67)

pull/84/head
chen.ma 3 years ago
parent 0444654e53
commit 2105dc6c21

@ -21,4 +21,9 @@ public class ManyPoolRunStateInfo extends PoolRunStateInfo {
*/
private String active;
/**
* state
*/
private String state;
}

@ -21,6 +21,18 @@ public class ArrayUtil {
return array == null || array.length == 0;
}
/**
* Is not empty.
*
* @param array
* @param <T>
* @return
*/
public static <T> boolean isNotEmpty(T[] array) {
return !isEmpty(array);
}
/**
* First match.
*

@ -62,6 +62,9 @@ public class ThreadPoolRunStateHandler extends AbstractThreadPoolRuntime {
String active = environment.getProperty("spring.profiles.active", "UNKNOWN");
manyPoolRunStateInfo.setActive(active.toUpperCase());
String threadPoolState = ThreadPoolStatusHandler.getThreadPoolState(pool);
manyPoolRunStateInfo.setState(threadPoolState);
return manyPoolRunStateInfo;
}

@ -0,0 +1,62 @@
package cn.hippo4j.starter.handler;
import cn.hutool.core.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Method;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* ThreadPool status handler.
*
* @author chen.ma
* @date 2022/1/18 20:54
*/
@Slf4j
public class ThreadPoolStatusHandler {
private static final String RUNNING = "Running";
private static final String TERMINATED = "Terminated";
private static final String SHUTTING_DOWN = "Shutting down";
private static final AtomicBoolean EXCEPTION_FLAG = new AtomicBoolean(Boolean.TRUE);
/**
* Get thread pool state.
*
* @param executor
* @return
*/
public static String getThreadPoolState(ThreadPoolExecutor executor) {
if (EXCEPTION_FLAG.get()) {
try {
Method runStateLessThan = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateLessThan");
ReflectUtil.setAccessible(runStateLessThan);
AtomicInteger ctl = (AtomicInteger) ReflectUtil.getFieldValue(executor, "ctl");
int shutdown = (int) ReflectUtil.getFieldValue(executor, "SHUTDOWN");
boolean runStateLessThanBool = ReflectUtil.invoke(executor, runStateLessThan, ctl.get(), shutdown);
if (runStateLessThanBool) {
return RUNNING;
}
Method runStateAtLeast = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateAtLeast");
ReflectUtil.setAccessible(runStateAtLeast);
int terminated = (int) ReflectUtil.getFieldValue(executor, "TERMINATED");
String resultStatus = ReflectUtil.invoke(executor, runStateAtLeast, ctl.get(), terminated) ? TERMINATED : SHUTTING_DOWN;
return resultStatus;
} catch (Exception ex) {
log.error("Failed to get thread pool status.", ex);
EXCEPTION_FLAG.set(Boolean.FALSE);
}
}
return "UNKNOWN";
}
}
Loading…
Cancel
Save