6

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?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
math
  • 8,514
  • 10
  • 53
  • 61
  • Left unclosed, it seems to keep a file descriptor occupied per file provided by the stream... which is really not what you may want dealing with large directories. – matanster Jan 19 '16 at 12:10

2 Answers2

5

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • So the authors of the tutorial just forgot about closing the streams? http://docs.oracle.com/javase/tutorial/essential/io/file.html#textfiles – math Jan 20 '15 at 15:15
  • 1
    No. They use the proper Automatic Resource Management idiom. – Marko Topolnik Jan 20 '15 at 15:16
  • 1
    That is what I want to know, what is this Idiom where is it described? Is the destructor closing the stream? I seem to have overlooked an essential part. – math Jan 20 '15 at 15:22
  • 1
    Found it, here: http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html Thank you so much! – math Jan 20 '15 at 15:26
2

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.

Jeff C.
  • 91
  • 4