Skip to content

Commit

Permalink
Fixed overlapping file lock exception
Browse files Browse the repository at this point in the history
- Updated SynchronizedFileStream class
- Updated CachedMapsFile#load() method
  • Loading branch information
josemmo committed Feb 24, 2024
1 parent b0f6330 commit 54c2bdc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -125,6 +126,7 @@ private void load() {
}

// Generate maps from image file
LOGGER.fine("Missed cache file \"" + path + "\"");
try {
generateFromImage();
tryToWriteToDisk();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -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;
}
}
}
}
}

0 comments on commit 54c2bdc

Please sign in to comment.