Java 在ThreadPoolExecutor中测试RejectedExecutionHandler

Java 在ThreadPoolExecutor中测试RejectedExecutionHandler,java,multithreading,Java,Multithreading,如何确保我的rejectedExecution方法有效 RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { logger.log(Level.INFO, "Name_[" + executorServiceName + "]: All threads busy, pro

如何确保我的rejectedExecution方法有效

 RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            logger.log(Level.INFO, "Name_[" + executorServiceName + "]: All threads busy, processing inline.");
            r.run();
        }
    });

我个人会创建这样一种情况,即我的
ExecutorService
将始终拒绝任务,并使用计数器检查是否调用了此任务

例如,我的代码可以是这样的:

// A single threaded executor service that cannot have more than 1 task in its task queue
// such that I know that if I provide at least 3 tasks, at least 1 task will be rejected. 
// Why 3? 1 task in the queue + 1 task executed by the thread of the pool 
// = max of tasks that the pool can manage at a given time, so if I add 1 it will be
// rejected.
ExecutorService executor = new ThreadPoolExecutor(
    1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1),
    Executors.defaultThreadFactory(), myHandler
);

// My Counter
AtomicInteger counter = new AtomicInteger();
// Some arbitrary task that lasts long enough to make sure that at least 3
// tasks will be submitted that will increment my counter once completed
Runnable task = () -> {
    try {
        Thread.sleep(1_000L);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        counter.incrementAndGet();
    }
};
try {
    // Submit 3 tasks
    executor.submit(task);
    executor.submit(task);
    executor.submit(task);
} finally {
    // Shutdown the pool and wait until all the submitted tasks have been executed
    executor.shutdown();
    executor.awaitTermination(1L, TimeUnit.MINUTES);
}
// Ensure that we have 3 tasks that have been executed
assertEquals(3, counter.get());
//在其任务队列中不能有多个任务的单线程执行器服务
//这样我就知道,如果我提供了至少3个任务,那么至少有1个任务将被拒绝。
//为什么是3?队列中的1个任务+1个由池的线程执行的任务
//=池在给定时间可以管理的最大任务数,因此,如果我添加1,它将是
//拒绝。
ExecutorService executor=新线程池执行器(
1,1,0L,TimeUnit.ms,新的LinkedBlockingQueue(1),
Executors.defaultThreadFactory(),myHandler
);
//我的柜台
AtomicInteger计数器=新的AtomicInteger();
//一些持续时间足够长的任意任务,以确保至少3
//将提交任务,完成后将增加我的计数器
可运行任务=()->{
试一试{
线程睡眠(1_000L);
}捕捉(中断异常e){
Thread.currentThread().interrupt();
}最后{
counter.incrementAndGet();
}
};
试一试{
//提交3项任务
执行人提交(任务);
执行人提交(任务);
执行人提交(任务);
}最后{
//关闭池并等待所有提交的任务执行完毕
executor.shutdown();
执行人等待终止(1L,时间单位:分钟);
}
//确保我们已经执行了3项任务
assertEquals(3,counter.get());

感谢您的回复。我试图在类外测试它,我无法更改现有类以关闭它。这种方法可以单独测试它。有什么方法可以用单元测试或其他方法来测试它吗?所有这些代码都可以进入单元测试类的测试方法中,唯一可以提供的就是myHandler