【问题标题】:Thread limit exceeded replacing blocked worker线程限制超出替换阻塞的工作人员
【发布时间】:2017-06-08 20:44:46
【问题描述】:

我正在使用AsyncHttpClient,并同时发出许多 http 请求。 我收到以下错误:

java.util.concurrent.RejectedExecutionException: Thread limit exceeded replacing blocked worker

我怎样才能做出一个新请求等待直到有空闲线程的行为?

我的代码:

public class MyClass {
    private AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();

    public JSONObject jsonFromUrl(String requestUrl) {
        CompletableFuture<Response> futureResponse = asyncHttpClient.prepareGet(requestUrl).
                addHeader("header-name", "header-value").execute().toCompletableFuture();
        try {
            Response response = futureResponse.get();
            ... handling response
        } catch (Exception e) {
            ... handling exception
        }
    }
}

【问题讨论】:

    标签: java http asynchronous asynchttpclient


    【解决方案1】:

    您可以通过将拒绝任务添加到执行程序的工作队列中来为处理拒绝任务的线程池实现和设置 RejectedExecutionHandler。

    http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/RejectedExecutionHandler.html

    threadPoolExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
            try {
                executor.getQueue().put(task);
            } catch (InterruptedException e) {
                // handle exception
            }
        }
    });
    

    请注意,在上面的实现中 put() 是一个阻塞操作,这意味着如果队列已满,它会等待直到有空间再次插入任务。

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      相关资源
      最近更新 更多