HttpClient在处理最大数量的请求时阻塞?

时间:2012-12-08 14:54:06

标签: java concurrency

我在整个应用程序中使用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 ...

我担心的是这很难看,即如果调用线程在获取时被中断,则返回的响应将为null。对于Java中的并发性,我也很绿,这种方法还有其他问题吗?

1 个答案:

答案 0 :(得分:1)

为了避免返回空响应,您可以使用的一个脏技巧是:

    boolean responseOK;
    do {
        try {
            semaphore.acquire();
            response = delegate.execute(request);
            semaphore.release();
            responseOK = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
            responseOK = false;
        }
    } while(!responseOK);

我知道有点脏,也许你可以在迭代之间添加一些休眠以防止它变成活动等待,但这是确保最终执行请求的一种方法(如果其他请求完成,那就是...)。

希望它有所帮助!