我在整个应用程序中使用 HttpClient 单例,在任何给定时间,它最多必须同时处理 3 个请求。我想在处理 3 个请求时阻止任何尝试执行请求的线程。到目前为止,这是我的代码:
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 ...
我担心的是这很难看,即如果调用线程在获取时被中断,那么返回的响应将为空。当谈到 Java 的并发性时,我也很绿色,这种方法还有其他问题吗?