2017-06-08 52 views
-1

我使用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 
     } 
    } 
} 

回答

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 
     } 
    } 
}); 

注意,在上面放實行()是一個阻塞操作,這意味着如果隊列已滿,等到再有足夠的空間來插入任務。