8211859: Avoid initializing AtomicBoolean from RandomAccessFile
authorredestad
Tue, 09 Oct 2018 14:30:06 +0200
changeset 52054 e7703e429767
parent 52053 7ecbaece746f
child 52055 9f154d0a59f6
child 56946 f020e1a82d09
8211859: Avoid initializing AtomicBoolean from RandomAccessFile Reviewed-by: alanb
src/java.base/share/classes/java/io/RandomAccessFile.java
--- a/src/java.base/share/classes/java/io/RandomAccessFile.java	Tue Oct 09 13:31:50 2018 +0100
+++ b/src/java.base/share/classes/java/io/RandomAccessFile.java	Tue Oct 09 14:30:06 2018 +0200
@@ -71,7 +71,9 @@
      */
     private final String path;
 
-    private final AtomicBoolean closed = new AtomicBoolean(false);
+    private final Object closeLock = new Object();
+
+    private volatile boolean closed;
 
     private static final int O_RDONLY = 1;
     private static final int O_RDWR =   2;
@@ -301,7 +303,7 @@
                 if (fc == null) {
                     this.channel = fc = FileChannelImpl.open(fd, path, true,
                         rw, false, this);
-                    if (closed.get()) {
+                    if (closed) {
                         try {
                             fc.close();
                         } catch (IOException ioe) {
@@ -638,14 +640,21 @@
      * @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();
+            // possible race with getChannel(), benign since
+            // FileChannel.close is final and idempotent
+            fc.close();
         }
 
         fd.closeAll(new Closeable() {