title: Why closing an Input Stream closes the associated File Descriptor as well, even the File Descriptor is shared among multiple streams ?
body: <p>I was just going through the implementation of <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/io/FileInputStream.java#FileInputStream.close%28%29" rel="nofollow">FileInputStream</a> and confused with the close method implementation, which is as given below,</p>
  
  <pre><code>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();
             }
          });
  }
  </code></pre>
  
  <p>This internally calls <code>closeAll</code> on <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/io/FileDescriptor.java#FileDescriptor.closeAll%28java.io.Closeable%29" rel="nofollow">FileDescriptor</a>, which releases all the Closables (not only the particular instance which calls the close). So a close call on an Input Stream closes all the streams share that FileDescriptor. </p>
  
  <pre><code>    FileInputStream is = 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());
  </code></pre>
  
  <p>In the above example <code>FileDescriptor</code> <code>fd</code> is shared among streams <code>is</code> and <code>is1</code>. A close call on <code>is</code> closes <code>is1</code> as well (basically <code>fd</code> is closed/released)</p>
  
  <p>My question is, FileInputStream has a flag to indicated its closed or not, but still why its closing the FileDescriptor when other active streams are pointing to it, making all of them fail/invalid, instead of just closing the calling instance and close the FileDescriptor when no other streams are pointing to it?</p>