Name: jl125535 Date: 03/12/2004
FULL PRODUCT VERSION :
java version "1.4.2"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2-b28)
Java HotSpot(TM) Client VM (build 1.4.2-b28, mixed mode)
A DESCRIPTION OF THE PROBLEM :
For various methods in the JDK API that return an already-open InputStream, OutputStream, Reader, or Writer, the JDK documentation (javadoc) does not specify whether or not it is the caller's responsibility to call 'close()' on the returned stream, or whether something else (e.g. the object on which the stream-returning method was called) may also close the returned stream (and under what circumstances) or what the consequences of the caller calling 'close()' will be.
Some of the methods for which I have seen this problem include:
Socket.getInputStream(), getOutputStream(), etc.
Process.getInputStream(), getOutputStream(), etc.
URL.openStream(), etc.
URLConnection.openInputStream(), etc.
not to mention various classes like FileInputStream, BufferedOutputStream, etc.
(For instance, is it sufficient to close the Reader object that a BufferedReader references, or is it necessary to close the BufferedReader object itself?)
As a result, there is a great deal of confusion on how to use these methods, and in many cases, the most commonly accepted method of using them is either unnecessarily inefficient (e.g. a stream getting ultimately closed by finalize() when garbage collection occurs) or outright wrong (e.g. having the object that created the stream close it, causing clients which may still be reading or writing to it to throw exceptions at the next access).
I believe strongly that EVERY method in the JDK which returns an InputStream, OutputStream, Reader, or Writer object should specify in its documentation:
1) If the caller is required to call close() on the returned stream.
2) If the class supplying the stream will ever call close() on the stream, and if so, at what times. (Does closing a socket also close its output stream? Or vice versa?)
3) What the consequences of calling close() on the returned stream will be, and how that will affect future calls to the stream-producing method or other methods on the stream-producing object. (Does closing a socket's output stream also close the socket?)
For instance, I have barely ever seen code which calls Runtime.exec() close the standard output and error streams attatched to the Process object that it returns (after reading data from them), and it is not clear from the API documentation whether this is necessary or useful. (Will it release file handles to the operating system? Is it necessary to close the streams even if no data needs to be read? etc.)
CUSTOMER SUBMITTED WORKAROUND :
Decompile the JDK and hope that the implementation doesn't change in the next release...?
(Incident Review ID: 185545)
======================================================================