0

我在整个应用程序中使用 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 的并发性时,我也很绿色,这种方法还有其他问题吗?

4

1 回答 1

1

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

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

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

希望能帮助到你!

于 2013-01-15T18:19:42.303 回答