【问题标题】:A HttpClient that blocks when a maximum number of requests are being processed?一个 HttpClient 在处理最大数量的请求时阻塞?
【发布时间】:2012-11-26 13:09:40
【问题描述】:

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

【问题讨论】:

    标签: java concurrency


    【解决方案1】:

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

        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 时使线程休眠 100 毫秒(即 Thread.sleep(100))
    • 在 Android 设备上忙着等待可能不是最好的主意,但这是一个解决方案。
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2021-02-11
    • 1970-01-01
    相关资源
    最近更新 更多