java - Why closing an Input Stream closes the associated File Descriptor as well, even the File Descriptor is shared among multiple streams ? -


i going through implementation of fileinputstream , confused close method implementation, given below,

public void close() throws ioexception {         synchronized (closelock) {             if (closed) {                 return;             }             closed = true;         }         if (channel != null) {            channel.close();         }          fd.closeall(new closeable() {             public void more ...close() throws ioexception {                close0();            }         }); } 

this internally calls closeall on filedescriptor, releases closables (not particular instance calls close). close call on input stream closes streams share filedescriptor.

    fileinputstream = new fileinputstream("some file");     bufferedinputstream br = new bufferedinputstream(is);      filedescriptor fd = is.getfd();      fileinputstream is1 = new fileinputstream(fd);     bufferedinputstream br1 = new bufferedinputstream(is1);      is.close();     system.out.println(is1.read()); 

in above example filedescriptor fd shared among streams is , is1. close call on is closes is1 (basically fd closed/released)

my question is, fileinputstream has flag indicated closed or not, still why closing filedescriptor when other active streams pointing it, making of them fail/invalid, instead of closing calling instance , close filedescriptor when no other streams pointing it?

if open fileinputstreams file object instead of filedescriptor you'll behavior expect:

file f = new file( ... ); inputstream in1 = new fileinputstream( f ); inputstream in2 = new fileinputstream( f ); 

you'll see in fileinputstream( file ) constructor source creates new filedescriptor each fileinputstream instead of sharing 1 passed in, happens in fileinputstream( filedescriptor ) constructor.

from javadoc, filedescriptor wraps underlying native os structure representing open file handle.

the whole purpose of inputstream.close() clean native resources. if 2 inputstreams sharing native file handle, when 1 gets closed other going affected well.

in alternative example provided above, 2 independent file handles created @ os / native level, can closed independently.


Comments