【问题标题】:How to determine if my task was accepted by thread pool and not rejected?如何确定我的任务是否被线程池接受并且没有被拒绝?
【发布时间】:2018-10-13 18:11:52
【问题描述】:

我有ThreadPoolExecutorService,核心池大小为 5,最大池大小为 10。我还将队列大小设置为 0。所以当我尝试 submit 11 个任务时 - 最后一个被拒绝。对于这些情况,我使用RejectedExecutionHandler。但是,从提交者线程我无法确定 - 我的任务是提交还是拒绝。 这是来自提交者线程的代码:

public void submitToAsyncExecution(Runnable r) {
  Future<Void> task = this.threadPool.submit(r)
  //is it possible to use returned future object to find out if my task is rejected or not ? 
}

我知道 - 替代方法是省略 RejectedExecutionHandler 并抛出拒绝异常,但是在我的情况下处理程序方法更合理。

【问题讨论】:

    标签: java spring multithreading


    【解决方案1】:

    如果我理解正确,您希望使用Future 的代码接收RejectedExecutionException 并处理它,而不是调用submitToAsyncExecution 的代码。

    我可以为您提供以下内容:

    public static Future<?> submitToAsyncExecution(Runnable r) {
        final ExecutorService s;
        try {
            return s.submit(r);
        } catch (RejectedExecutionException e) {
            final CompletableFuture<Void> cf = new CompletableFuture<>();
            // You can wrap it or create another exception if needed.
            cf.completeExceptionally(e);
            return cf;
        }
    }
    

    它捕获异常并从中创建一个 Future。每一段使用它的代码都会收到拒绝的异常并处理它。

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 1970-01-01
      • 2014-08-22
      • 2023-03-25
      • 2020-11-13
      • 2020-02-05
      • 1970-01-01
      • 2018-02-04
      • 2012-02-16
      相关资源
      最近更新 更多