Skip to content

Commit

Permalink
动态代理实现线程池拒绝策略执行次数统计. (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
magestacks committed Feb 17, 2022
1 parent e09d5d0 commit 32bf86c
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cn.hippo4j.starter.core;

import lombok.AllArgsConstructor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;

/**
* Rejected proxy invocation handler.
*
* @author chen.ma
* @date 2022/2/17 19:45
*/
@AllArgsConstructor
public class RejectedProxyInvocationHandler implements InvocationHandler {

private final Object target;

private final AtomicInteger rejectCount;

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
rejectCount.incrementAndGet();
try {
return method.invoke(target, args);
} catch (InvocationTargetException ex) {
throw ex.getCause();
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package cn.hippo4j.starter.test;

import cn.hippo4j.starter.core.DynamicThreadPoolExecutor;
import cn.hippo4j.starter.toolkit.thread.ThreadPoolBuilder;
import cn.hippo4j.starter.toolkit.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

/**
* Rejected execution handler proxy test.
*
* @author chen.ma
* @date 2022/2/17 19:52
*/
@Slf4j
public class RejectedExecutionHandlerProxyTest {

public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
test(i + "");
}
}

private static void test(String threadPoolId) {
ThreadPoolExecutor executor = ThreadPoolBuilder.builder()
.threadPoolId(threadPoolId)
.threadFactory(threadPoolId)
.poolThreadSize(1, 1)
.workQueue(new LinkedBlockingQueue(1))
.dynamicPool()
.build();


for (int i = 0; i < 300; i++) {
try {
executor.execute(() -> ThreadUtil.sleep(Integer.MAX_VALUE));
} catch (Exception ex) {
log.error("ThreadPool name :: {}, Exception :: ", Thread.currentThread().getName(), ex);
}
}

ThreadUtil.sleep(1000);

DynamicThreadPoolExecutor dynamicThreadPoolExecutor = (DynamicThreadPoolExecutor) executor;
Integer rejectCount = dynamicThreadPoolExecutor.getRejectCount();
log.info("ThreadPool name :: {}, Reject count :: {}", Thread.currentThread().getName(), rejectCount);
}
}

0 comments on commit 32bf86c

Please sign in to comment.