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

Graham Borland picture Graham Borland · Jun 23, 2014 · Viewed 8.8k times · Source
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()?

Answer

omu_negru picture omu_negru · Jun 23, 2014

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