From 54c2bdc3012e0dca52e6d17cfb3e8c13c2681c06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Miguel=20Moreno?= Date: Sat, 24 Feb 2024 13:37:01 +0100 Subject: [PATCH] Fixed overlapping file lock exception - Updated SynchronizedFileStream class - Updated CachedMapsFile#load() method --- .../bukkit/plugin/storage/CachedMapsFile.java | 2 ++ .../storage/SynchronizedFileStream.java | 28 +++++++++++++++++-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/josemmo/bukkit/plugin/storage/CachedMapsFile.java b/src/main/java/io/josemmo/bukkit/plugin/storage/CachedMapsFile.java index 8207f14..8307eae 100644 --- a/src/main/java/io/josemmo/bukkit/plugin/storage/CachedMapsFile.java +++ b/src/main/java/io/josemmo/bukkit/plugin/storage/CachedMapsFile.java @@ -114,6 +114,7 @@ public int getDelay() { private void load() { // Try to load maps from disk if (exists() && getLastModified() > imageFile.getLastModified()) { + LOGGER.fine("Found warm cache file \"" + path + "\""); try { loadFromDisk(); return; @@ -125,6 +126,7 @@ private void load() { } // Generate maps from image file + LOGGER.fine("Missed cache file \"" + path + "\""); try { generateFromImage(); tryToWriteToDisk(); diff --git a/src/main/java/io/josemmo/bukkit/plugin/storage/SynchronizedFileStream.java b/src/main/java/io/josemmo/bukkit/plugin/storage/SynchronizedFileStream.java index 7410d16..2b1260e 100644 --- a/src/main/java/io/josemmo/bukkit/plugin/storage/SynchronizedFileStream.java +++ b/src/main/java/io/josemmo/bukkit/plugin/storage/SynchronizedFileStream.java @@ -4,6 +4,9 @@ import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.RandomAccessFile; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.OverlappingFileLockException; import java.nio.file.Path; /** @@ -17,10 +20,29 @@ public class SynchronizedFileStream extends RandomAccessFile { * @param readOnly Whether to open stream in read-only mode * @throws IOException if failed to acquire lock */ - @Blocking public SynchronizedFileStream(@NotNull Path path, boolean readOnly) throws IOException { super(path.toFile(), readOnly ? "r" : "rw"); - //noinspection ResultOfMethodCallIgnored - getChannel().lock(0L, Long.MAX_VALUE, readOnly); + waitForLock(readOnly); + } + + /** + * Wait for lock to be released + * @param readOnly Whether to acquire read-only (shared) lock + */ + @Blocking + private void waitForLock(boolean readOnly) throws IOException { + FileChannel channel = getChannel(); + FileLock lock = null; + while (lock == null) { + try { + lock = channel.lock(0L, Long.MAX_VALUE, readOnly); + } catch (OverlappingFileLockException e) { + try { + Thread.sleep(20); + } catch (InterruptedException __) { + throw e; + } + } + } } }