Skip to content

Instantly share code, notes, and snippets.

@serac
Created May 8, 2013 15:12
Show Gist options
  • Save serac/5541134 to your computer and use it in GitHub Desktop.
Save serac/5541134 to your computer and use it in GitHub Desktop.
Demonstrate Java NIO file locking capability.
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.InterruptedException;
import java.lang.Thread;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
public class MultiThreadedWriteTest
{
public static void main(final String[] args) throws Exception
{
if (args.length < 1) {
System.out.println("Usage: MultiThreadedWriteTest /path/to/file");
return;
}
final Thread t1 = new Thread(new Writer(new File(args[0])), "thread-1");
final Thread t2 = new Thread(new Writer(new File(args[0])), "thread-2");
t1.start();
t2.start();
t1.join();
t2.join();
}
static class Writer implements Runnable
{
private final File file;
public Writer(final File file) {
this.file = file;
}
public void run() {
FileChannel channel = null;
FileLock lock = null;
final ByteBuffer buffer = ByteBuffer.allocate(100);
final String line = "Hello from thread " + Thread.currentThread().getName() + "\n";
buffer.put(line.getBytes());
buffer.flip();
try {
channel = new FileOutputStream(file).getChannel();
int maxTries = 4;
int count = 0;
do {
try {
lock = channel.lock();
} catch (OverlappingFileLockException e) {
System.out.println(Thread.currentThread().getName() + " can't get file lock. Waiting 500ms.");
Thread.sleep(500);
count++;
}
} while (lock == null && count < maxTries);
if (lock != null) {
System.out.println(Thread.currentThread().getName() + " writing to " + file);
channel.write(buffer);
} else {
System.out.println(Thread.currentThread().getName() + " giving up after " + count + " tries");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (lock != null) {
try {
lock.release();
} catch (Exception e) {
System.out.println("Failed releasing lock");
e.printStackTrace();
}
}
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
System.out.println("Failed closing file channel");
e.printStackTrace();
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment