Java 在处理最大数量的请求时阻塞的HttpClient?
我在整个应用程序中使用HttpClient单例,在任何给定时间,它最多必须同时处理3个请求。我想阻止在处理3个请求时尝试执行请求的任何线程。以下是我目前的代码:Java 在处理最大数量的请求时阻塞的HttpClient?,java,concurrency,Java,Concurrency,我在整个应用程序中使用HttpClient单例,在任何给定时间,它最多必须同时处理3个请求。我想阻止在处理3个请求时尝试执行请求的任何线程。以下是我目前的代码: public class BlockingHttpClient implements HttpClient { private static final int MAX_CONNECTIONS = 3; private static BlockingHttpClient instance; private H
public class BlockingHttpClient implements HttpClient {
private static final int MAX_CONNECTIONS = 3;
private static BlockingHttpClient instance;
private HttpClient delegate;
private Semaphore semaphore;
private BlockingHttpClient() {
delegate = new DefaultHttpClient();
semaphore = new Semaphore(MAX_CONNECTIONS, true);
// Set delegate with a thread-safe connectionmanager and params etc..
}
public static synchronized BlockingHttpClient getInstance() {
if(instance == null) {
instance = new BlockingHttpClient();
}
return instance;
}
@Override
public HttpResponse execute(HttpUriRequest request) throws IOException,
ClientProtocolException {
HttpResponse response = null;
try {
semaphore.acquire();
response = delegate.execute(request);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
return response;
}
.... the other delegated methods look the same ...
我担心的是这很难看,即如果调用线程get在acquring时被中断,那么返回的响应将为null。对于Java中的并发性,我也非常熟悉,这种方法还有其他问题吗?为了避免返回空响应,您可以使用一个肮脏的技巧:
boolean responseOK;
do {
try {
semaphore.acquire();
response = delegate.execute(request);
semaphore.release();
responseOK = true;
} catch (InterruptedException e) {
e.printStackTrace();
responseOK = false;
}
} while(!responseOK);
我知道这有点脏,也许您可以在迭代之间添加一些睡眠,以防止它变成活动等待,但这是一种确保请求最终将被执行的方法(如果其他请求完成,也就是…)
希望有帮助 是的,它浪费CPU时间。一个快速的解决方案是,每当发现InterruptedException(即thread.sleep(100))时,在Android设备上忙着等待线程100毫秒,这可能不是最好的办法,不过这是一个解决方案。