【问题标题】:Is InputStream.close() a blocking call in java?InputStream.close() 是java中的阻塞调用吗?
【发布时间】:2012-11-27 13:40:41
【问题描述】:

我从输入流中读取数据,并在 finally 块中尝试通过调用 in.close(); 来关闭它; 但是 main 的执行被阻止了。出路是什么?

根据建议,我使用的代码是,

if (!processed) {
                System.out.println("in processed");
                byte[] contents = new byte[(int) fileSplit.getLength()];
                Path file = fileSplit.getPath();
                FileSystem fs = file.getFileSystem(conf);
                FSDataInputStream in = null;
                try {
                    in = fs.open(file);
                    IOUtils.readFully(in, contents, 0, contents.length);

                    value.set(contents, 0, contents.length);
                } finally {
                    System.out.println("before close stream");
                    IOUtils.closeStream(in);
                }
                processed = true;
                return true;
            }
            System.out.println("out of processed");
            return false;
        }

【问题讨论】:

  • 不显示其他人无法轻易展示的源代码。
  • @AdityaJain @ ILLA:完成:)
  • 是控制台上的“关闭流之前”打印
  • @BhavikShah : 是的..我把那个打印出来了..

标签: java io inputstream


【解决方案1】:

java.io.InputStream.close 没有阻塞,至少 API 从来没有这么说。比较 InputStream.read

 Reads the next byte of data from the input stream. The value byte is
 returned as an <code>int</code> in the range <code>0</code> to
 <code>255</code>. If no byte is available because the end of the stream
 has been reached, the value <code>-1</code> is returned. This method
 blocks until input data is available, the end of the stream is detected,
 or an exception is thrown.

和 InputStream.close

  Closes this file input stream and releases any system resources
  associated with the stream.

至于解决您的问题,我建议使用 Java 7 Files.readAllBytes 并忘记您的难题。

【讨论】:

  • 不能使用 Files.readAllBytes,因为这是架构的一部分,需要通过定义开始和结束位置并进入缓冲区来完成读取。
  • 所有流上的 I/O 阻塞。
猜你喜欢
  • 2010-10-13
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多