src/java.base/share/classes/java/io/FileOutputStream.java

Print this page
rev 11067 : 8025619.01

@@ -24,10 +24,11 @@
  */
 
 package java.io;
 
 import java.nio.channels.FileChannel;
+import java.util.concurrent.atomic.AtomicBoolean;
 import sun.misc.SharedSecrets;
 import sun.misc.JavaIOFileDescriptorAccess;
 import sun.nio.ch.FileChannelImpl;
 
 

@@ -74,12 +75,11 @@
      * The path of the referenced file
      * (null if the stream is created with a file descriptor)
      */
     private final String path;
 
-    private final Object closeLock = new Object();
-    private volatile boolean closed = false;
+    private AtomicBoolean closed = new AtomicBoolean(false);
 
     /**
      * Creates a file output stream to write to the file with the
      * specified name. A new <code>FileDescriptor</code> object is
      * created to represent this file connection.

@@ -339,16 +339,14 @@
      *
      * @revised 1.4
      * @spec JSR-51
      */
     public void close() throws IOException {
-        synchronized (closeLock) {
-            if (closed) {
+        if (!closed.compareAndSet(false, true)) {
+            // if compareAndSet() returns false closed was already true
                 return;
             }
-            closed = true;
-        }
 
         if (channel != null) {
             channel.close();
         }
 

@@ -395,10 +393,17 @@
      */
     public FileChannel getChannel() {
         synchronized (this) {
             if (channel == null) {
                 channel = FileChannelImpl.open(fd, path, false, true, this);
+                if (closed.get()) {
+                    try {
+                        channel.close();
+                    } catch (IOException ioe) {
+                        throw new InternalError(ioe); // should not happen
+                    }
+                }
             }
             return channel;
         }
     }