Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

stream

nio2

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?

like image 518
math Avatar asked Jan 20 '15 14:01

math


2 Answers

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.

like image 172
Marko Topolnik Avatar answered Oct 19 '22 07:10

Marko Topolnik


You can do this conveniently with the new try with resources option.

try(/*initialize resources here*/)
{
}

They will automatically be closed after the try block. Add a catch as necessary.

like image 35
Jeff C. Avatar answered Oct 19 '22 07:10

Jeff C.