java—如何在rejectedexecution中获取一些业务参数?

fkaflof6  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(508)

java多线程执行任务,并显式构造 ThreadPoolExecutor 就像下面一样

final ExecutorService threadPool = new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1), myRejectedExecutionHandler);

并通过下面的方式提交任务

for (int i = 0; i < count; i++) {
    int articleId = i;
    CompletableFuture.supplyAsync(() -> articleId, threadPool);

}

现在我想定制 rejectedExecutionHandler ```
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);

但我怎么才能拿到证件?因为我想登录被拒绝的articleid `rejectedExecution` 例如

log.warn("article: {} is rejected, please process it manually", articleId);

6za6bjd0

6za6bjd01#

我的解决方案是:不使用自定义rejectedexecutionhandler并捕获rejectedexecutionexception

catchRejectedException(()->CompletableFuture.supplyAsync(() -> articleId, threadPool), articleId);

private void catchRejectedException(Runnable task, int articleId) {
    try {
        task.run();
    } catch (RejectedExecutionException e) {
        log.error("article: {} is rejected", articleId, e);
    }
}

相关问题