Skip to content

Instantly share code, notes, and snippets.

@aerodame
Last active March 10, 2025 19:54
Show Gist options
  • Save aerodame/e69aaf0b513c6dad725e648ab3afd7b0 to your computer and use it in GitHub Desktop.
Save aerodame/e69aaf0b513c6dad725e648ab3afd7b0 to your computer and use it in GitHub Desktop.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
public class ConcurrentPartialFileLocking {
private static final String FILENAME = "concurrent_partial_locked_file.txt";
private static final String PHRASE = "The quick brown fox jumped over the lazy dog.";
private static final int FILE_SIZE = PHRASE.length();
public static void main(String[] args) {
createFileWithPhrase(FILENAME, PHRASE); // 1. Create the file with the phrase.
int halfSize = FILE_SIZE / 2; // 2. Create and start two threads.
Thread thread1 = new Thread(new FileRegionTask(FILENAME, 0, halfSize, "Thread 1"));
Thread thread2 = new Thread(new FileRegionTask(FILENAME, halfSize, FILE_SIZE - halfSize, "Thread 2"));
thread1.start();
thread2.start();
try { // Wait for the threads to finish.
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.err.println("Main thread interrupted: " + e.getMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment