From 8ecd5dd6ef7ada4d6ecc27303a0ef48797fad1ed Mon Sep 17 00:00:00 2001 From: mjpt777 Date: Tue, 31 May 2022 10:35:36 +0100 Subject: [PATCH] Avoid racing calls to close MarkFile. --- agrona/src/main/java/org/agrona/MarkFile.java | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/agrona/src/main/java/org/agrona/MarkFile.java b/agrona/src/main/java/org/agrona/MarkFile.java index b4e4a6d7c..60230c5c4 100644 --- a/agrona/src/main/java/org/agrona/MarkFile.java +++ b/agrona/src/main/java/org/agrona/MarkFile.java @@ -22,6 +22,7 @@ import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.IntConsumer; @@ -46,7 +47,7 @@ public class MarkFile implements AutoCloseable private final MappedByteBuffer mappedBuffer; private final UnsafeBuffer buffer; - private volatile boolean isClosed = false; + private final AtomicBoolean isClosed = new AtomicBoolean(); /** * Create a directory and mark file if none present. Checking if an active Mark file exists and is active. @@ -230,7 +231,7 @@ public MarkFile(final UnsafeBuffer buffer, final int versionFieldOffset, final i */ public boolean isClosed() { - return isClosed; + return isClosed.get(); } /** @@ -238,14 +239,9 @@ public boolean isClosed() */ public void close() { - if (!isClosed) + if (isClosed.compareAndSet(false, true)) { - if (null != mappedBuffer) - { - BufferUtil.free(mappedBuffer); - } - - isClosed = true; + BufferUtil.free(mappedBuffer); } }