【问题标题】:Java interrupt inputstream without close() method没有 close() 方法的 Java 中断输入流
【发布时间】:2017-04-18 06:34:40
【问题描述】:

所以,我有一段代码连接到服务器并以 2mb 的块下载大约 2gb 的内容。所有这些都在一个线程中完成。有时我需要停止线程,因为主线程中发生了不同的错误,或者我想关闭应用程序。我的问题是我无法关闭连接的 InputStream。每次我调用 close() 方法时,InputStream 都会消耗服务器发送的整个 2gb。 有没有办法在不消耗服务器发送的整个内容的情况下关闭 InputStream?

fos.getChannel().transferFrom(Channels.newChannel(res.getEntity().getContent()), bytes_read, CHUNK_SIZE);
res.getEntity().getContent().close();

res.getEntity().getContent()返回从连接创建的 InputStream。

res 是一个 apache httpResponse。

fos 是我要将响应内容保存到的 FileOutputStream。

编辑:线程的运行方法

CHUNK_SIZE: int: 2mb in bytes

@Override
public void run() {
    int expectedCode;
    do{
        try {
            client = HttpClients.createDefault();

            HttpGet req = new HttpGet(url.toString());
            HttpResponse res = client.execute(req);

            if (res.getStatusLine().getStatusCode() == 200) {
                while(running){
                    fos.getChannel().transferFrom(Channels.newChannel(res.getEntity().getContent()), bytes_read, CHUNK_SIZE);
                }
            } else {
                log.error(Languages.getString("Download.2") + expectedCode); //$NON-NLS-1$
            }
        } catch (Exception ex) {
            log.error(ex);
        } finally{
            try{
                rbc.close();
            } catch(Exception ex){
                log.error(ex);
            }
        }
    }while(!isFinished() && running);
    try{
        rbc.close();
        fos.close();
        client.close();
    } catch(Exception ex){
        log.error(ex);
    }
}

【问题讨论】:

  • 所以每当你调用 .close() 时,线程都会被阻塞,直到所有 2Gb 的数据都被传输完?
  • .close() 方法阻塞线程并接收直到所有 2gb 都被读取但它不传输任何字节它只清除输入流
  • 也许,.close() 不是罪魁祸首,而是它周围的代码。 InputStream 的实际实现是什么?你能发布一些附加代码吗?

标签: java apache http iostream


【解决方案1】:

Apache HttpClient 的底层实现使用 ContentLengthInputStream 来保存响应。正如在 ContentLengthInputStream 中提到的,.close() 方法从不真正关闭流,而是读取所有剩余的字节,直到达到 Content-Length。

解决方案:不要调用res.getEntity().getContent().close(),而是尝试res.close()req.abort()

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2011-06-12
    • 2017-04-03
    • 2016-06-07
    • 2015-07-21
    相关资源
    最近更新 更多