src/share/classes/java/io/RandomAccessFile.java

Print this page

        

@@ -227,11 +227,11 @@
         }
         if (name == null) {
             throw new NullPointerException();
         }
         fd = new FileDescriptor();
-        fd.attach(this);
+        fd.incrementAndGetUseCount();
         open(name, imode);
     }
 
     /**
      * Returns the opaque file descriptor object associated with this

@@ -240,13 +240,11 @@
      * @return     the file descriptor object associated with this stream.
      * @exception  IOException  if an I/O error occurs.
      * @see        java.io.FileDescriptor
      */
     public final FileDescriptor getFD() throws IOException {
-        if (fd != null) {
-            return fd;
-        }
+        if (fd != null) return fd;
         throw new IOException();
     }
 
     /**
      * Returns the unique {@link java.nio.channels.FileChannel FileChannel}

@@ -268,10 +266,21 @@
      */
     public final FileChannel getChannel() {
         synchronized (this) {
             if (channel == null) {
                 channel = FileChannelImpl.open(fd, true, rw, this);
+
+                /*
+                 * FileDescriptor could be shared by FileInputStream or
+                 * FileOutputStream.
+                 * Ensure that FD is GC'ed only when all the streams/channels
+                 * are done using it.
+                 * Increment fd's use count. Invoking the channel's close()
+                 * method will result in decrementing the use count set for
+                 * the channel.
+                 */
+                fd.incrementAndGetUseCount();
             }
             return channel;
         }
     }
 

@@ -566,18 +575,26 @@
                 return;
             }
             closed = true;
         }
         if (channel != null) {
+            /*
+             * Decrement FD use count associated with the channel. The FD use
+             * count is incremented whenever a new channel is obtained from
+             * this stream.
+             */
+            fd.decrementAndGetUseCount();
             channel.close();
         }
-        fd.closeAll(new Closeable() {
-            public void close() throws IOException {
+
+        /*
+         * Decrement FD use count associated with this stream.
+         * The count got incremented by FileDescriptor during its construction.
+         */
+        fd.decrementAndGetUseCount();
                close0();
            }
-        });
-    }
 
     //
     //  Some "reading/writing Java data types" methods stolen from
     //  DataInputStream and DataOutputStream.
     //