【问题标题】:Apache HttpClient Official Example - Releasing Resources methodApache HttpClient 官方示例 - 释放资源方法
【发布时间】:2015-05-19 14:03:06
【问题描述】:

在这个 Apache HttpClient 的官方示例中,没有提到释放请求或响应对象。它们是作为 httpclient.close() 的一部分发布还是需要用某些东西覆盖 releaseResources 方法?

final CountDownLatch latch2 = new CountDownLatch(1);
final HttpGet request3 = new HttpGet("http://www.apache.org/");
HttpAsyncRequestProducer producer3 = HttpAsyncMethods.create(request3);
AsyncCharConsumer<HttpResponse> consumer3 = new AsyncCharConsumer<HttpResponse>() {

    HttpResponse response;

    @Override
    protected void onResponseReceived(final HttpResponse response) {
        this.response = response;
    }

    @Override
    protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
        // Do something useful
    }

    @Override
    protected void releaseResources() {
    }

    @Override
    protected HttpResponse buildResult(final HttpContext context) {
        return this.response;
    }

};
httpclient.execute(producer3, consumer3, new FutureCallback<HttpResponse>() {

    public void completed(final HttpResponse response3) {
        latch2.countDown();
        System.out.println(request2.getRequestLine() + "->" + response3.getStatusLine());
    }

    public void failed(final Exception ex) {
        latch2.countDown();
        System.out.println(request2.getRequestLine() + "->" + ex);
    }

    public void cancelled() {
        latch2.countDown();
        System.out.println(request2.getRequestLine() + " cancelled");
    }

});
latch2.await();

} finally {
    httpclient.close();
}

【问题讨论】:

    标签: apache httpclient apache-httpclient-4.x http-get


    【解决方案1】:

    仅当消费者使用文件、管道等系统资源时才需要覆盖#releaseResources()。如果响应内容始终保存在内存中,它会以正常方式进行GC。

    【讨论】:

    • 感谢奥列格的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多