Do readers need to be closed, even if the underlying InputStream
is closed somewhere else?
No they absolutely don't need to be in that scenario. But it is generally a good idea to close them anyway.
Can I get a memory leak by not closing readers?
No, there is no memory leak, assuming that the Reader
itself becomes unreachable once you have finished with it. And besides, a Reader
doesn't typically use a lot of memory.
The more important question is whether you can get a resource leak by not closing a Reader
. The answer is ... it depends.
If you can guarantee that the underlying InputStream
will always be closed somewhere else in the application, then that takes care of possible memory leaks.
If you can't guarantee that, then there is a risk of a resource leak. The underlying OS level file descriptors are a limited resource in (for example) Linux. If a JVM doesn't close them, they can run out and a certain system calls will start to fail unexpectedly.
But if you do close the Reader
then the underlying InputStream
will be closed.
Calling close()
more than once on a InputStream
is harmless, and costs almost nothing.
The only case where you shouldn't close the Reader
is when it would be wrong to close the underlying InputStream
. For example, if you close a SocketInputStream
the rest of the application may not be able to reestablish the network connection. Likewise, the InputStream
associated with System.in
usually cannot be reopened.
In that case, it is actually safe to allow the Reader
you create in your method to be garbage collected. Unlike InputStream
, a typical Reader
class doesn't override Object::finalize()
to close its source of data.
@Pshemo brought up an important point about system design.
If you are accepting an InputStream
as an argument, then it may be wrong to wrap it with a local Reader
... especially a BufferedReader
. A BufferedReader
is liable to read-ahead on the stream. If the stream is going to be used by the caller after your method returns, then any data that has been read into the buffer but not consumed by this method is liable to be lost.
A better idea would be for the caller to pass a Reader
. Alternatively, this method should be documented as taking ownership of the InputStream
. And in that case, it should always close()
it.
BufferedReader
, but accept it as argument. This way you will have one BufferedReader in your application and can close it when it is no longer needed which will also close underlyingInputStream
. – Astridastride