< prev index next >

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

Print this page
rev 15897 : 8168640: (fc) Avoiding AtomicBoolean in FileInput/-OutputStream improves startup
Reviewed-by: alanb, shade, plevart

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

@@ -75,11 +74,13 @@
      * The path of the referenced file
      * (null if the stream is created with a file descriptor)
      */
     private final String path;
 
-    private final AtomicBoolean closed = new AtomicBoolean(false);
+    private final Object closeLock = new Object();
+
+    private volatile boolean closed;
 
     /**
      * 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,14 +340,19 @@
      *
      * @revised 1.4
      * @spec JSR-51
      */
     public void close() throws IOException {
-        if (!closed.compareAndSet(false, true)) {
-            // if compareAndSet() returns false closed was already true
+        if (closed) {
+            return;
+        }
+        synchronized (closeLock) {
+            if (closed) {
             return;
         }
+            closed = true;
+        }
 
         FileChannel fc = channel;
         if (fc != null) {
            fc.close();
         }

@@ -397,11 +403,11 @@
         if (fc == null) {
             synchronized (this) {
                 fc = this.channel;
                 if (fc == null) {
                     this.channel = fc = FileChannelImpl.open(fd, path, false, true, this);
-                    if (closed.get()) {
+                    if (closed) {
                         try {
                             fc.close();
                         } catch (IOException ioe) {
                             throw new InternalError(ioe); // should not happen
                         }
< prev index next >