Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Java 8 Stream class AutoCloseable?

In Java 8, the Stream class implements AutoCloseable. This means that a stream instance should be closed explicitly.

I understand why file handlers and DB connections are closeable. But why streams?

like image 747
David Limkys Avatar asked Mar 02 '14 07:03

David Limkys


People also ask

Are streams AutoCloseable?

Streams have a BaseStream. close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files. lines(Path, Charset)) will require closing.

Why is Java 8 streaming so fast?

In Java8 Streams, performance is achieved by parallelism, laziness, and using short-circuit operations, but there is a downside as well, and we need to be very cautious while choosing Streams, as it may degrade the performance of your application. Let us look at these factors which are meant for Streams' performance.

Why streams in Java 8 are lazy?

Streams are lazy because intermediate operations are not evaluated until terminal operation is invoked. Each intermediate operation creates a new stream, stores the provided operation/function and return the new stream. The pipeline accumulates these newly created streams.

What is the use of AutoCloseable in Java?

The close() method of an AutoCloseable object is called automatically when exiting a try -with-resources block for which the object has been declared in the resource specification header. This construction ensures prompt release, avoiding resource exhaustion exceptions and errors that may otherwise occur.


1 Answers

I think the current documentation/javadoc of Stream is pretty clear:

Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)

like image 77
LaurentG Avatar answered Oct 10 '22 10:10

LaurentG