我正在使用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
}
}
}
答案 0 :(得分:2)
您可以为处理被拒绝任务的线程池实现和设置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()是一个阻塞操作,这意味着如果队列已满,它会等到再次有空间插入任务。