javastreamnio2

Should I close Streams created with java.nio.file.Files.newInputStream?


In the stream tutorial, nothing is said about closing streams gained from Files.newInputStream( path ). Only some obscure:

Whether the returned stream is asynchronously closeable and/or interruptible is highly file system provider specific and therefore not specified.

What is "asyncronously" in this context? If I close the stream explicitly or if another thread closes the stream asyncronously?


Solution

  • You definitely must close the obtained InputStream, just like all others. The term "asynchronously closeable" refers to the ability to close the stream while another thread is blocked on an I/O operation on it.

    From InterruptibleChannel documentation:

    A channel that implements this interface is asynchronously closeable: If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the channel's close method. This will cause the blocked thread to receive an AsynchronousCloseException.