gpt4 book ai didi

java - 在 ThreadPoolExecutor 中测试 RejectedExecutionHandler

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:12 24 4
gpt4 key购买 nike

我如何确保我的 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());

关于java - 在 ThreadPoolExecutor 中测试 RejectedExecutionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com