Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do terminal operations close the stream?

Tags:

dirPath contains 200k files. I want to read them one by one and do some processing. The following snippet causes java.nio.file.FileSystemException: dirPath/file-N Too many open files. Isn't the terminal operation forEach() supposed to close the open stream (i.e. the open file) before moving to the next one? In other words, do I have to add try-with-resources for the streamed files?

Files.list(dirPath)      .forEach(filePath -> {               Files.lines(filePath).forEach() { ... }               }); 
like image 363
mossaab Avatar asked Nov 18 '14 14:11

mossaab


People also ask

What is terminal operation on stream?

A terminal operation in Java is a method applied to a stream as the final step. 2. Return Type. They only return another stream. They return final result.

What happens when one calls two terminal operations on a stream?

No. You cannot use a stream multiple times. What you can do is , you can collect the stream in a list and then you can call the map and forEach functions which accepts a lambda.

Can we have stream without terminal operation?

Avoiding the Use of the Reduce MethodA stream does not process any data if it does not end with a terminal operation. We already covered the terminal operation reduce() , and you saw several terminal operations in other examples. Let us now present the other terminal operations you can use on a stream.

What is the difference between intermediate and terminal operations on stream?

The distinction between this operations is that an intermediate operation is lazy while a terminal operation is not. When you invoke an intermediate operation on a stream, the operation is not executed immediately. It is executed only when a terminal operation is invoked on that stream.


1 Answers

No forEach does not close the stream (created by Files.list or Files.lines). It is documented in the javadoc, for example for Files.list:

The returned stream encapsulates a Reader. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

like image 112
assylias Avatar answered Sep 29 '22 14:09

assylias