Skip to content

Instantly share code, notes, and snippets.

@aerodame
Last active March 10, 2025 20:02
Show Gist options
  • Save aerodame/449a91e174fda909d5c87d3b999decb8 to your computer and use it in GitHub Desktop.
Save aerodame/449a91e174fda909d5c87d3b999decb8 to your computer and use it in GitHub Desktop.
@Override
public void run() {
File file = new File(filename);
try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel()) {
System.out.println(threadName + " attempting to acquire a lock on region [" +
startPosition + ", " + (startPosition + regionSize) + "]");
FileLock lock = null;
try {
lock = channel.lock(startPosition, regionSize, false); // Exclusive lock.
if (lock != null) {
System.out.println(threadName + " acquired lock on the specified region!");
// Simulate working with the file.
System.out.println(threadName + " Performing operations on the locked region...");
// Read and print the content of the locked region.
ByteBuffer buffer = ByteBuffer.allocate((int) regionSize);
channel.position(startPosition);
channel.read(buffer);
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
System.out.println(threadName + " Region Content: \"" + new String(bytes) + "\"");
Thread.sleep(2000); // Simulate some work.
System.out.println(threadName + " Finished operations on the locked region.");
}
} catch (OverlappingFileLockException e) {
System.err.println(threadName + ": File region is already locked by another process or thread.");
} catch (IOException | InterruptedException e) {
System.err.println(threadName + ": Error during lock operation: " + e.getMessage());
} finally {
if (lock != null) {
System.out.println(threadName + " Attempting to release lock.");
lock.release();
System.out.println(threadName + " Lock released.");
}
}
} catch (IOException e) {
System.err.println(threadName + ": Error accessing file: " + e.getMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment