Search code examples
javainputstreambufferedinputstream

When I close a BufferedInputStream, is the underlying InputStream also closed?


InputStream in = SomeClass.getInputStream(...);
BufferedInputStream bis = new BufferedInputStream(in);

try {
    // read data from bis
} finally {
    bis.close();
    in.close();    
}

The javadoc for BufferedInputStream.close() doesn't mention whether or not the underlying stream is closed:

Closes this input stream and releases any system resources associated with the stream. Once the stream has been closed, further read(), available(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.

Is the explicit call to in.close() necessary, or should it be closed by the call to bis.close()?


Solution

  • From the source code of BufferedInputStream :

    public void close() throws IOException {
        byte[] buffer;
        while ( (buffer = buf) != null) {
            if (bufUpdater.compareAndSet(this, buffer, null)) {
                InputStream input = in;
                in = null;
                if (input != null)
                    input.close();
                return;
            }
            // Else retry in case a new buf was CASed in fill()
        }
    }
    

    So the answer would be : YES