I try to lock a file and write to it with the code below:
public class TrainSetBuildTask implements Runnable {
private String pathname;
public TrainSetBuildTask(String pathname){
this.pathname = pathname;
}
@Override
public void run() {
try {
String content = "content\n";
//write to a file
FileOutputStream os = new FileOutputStream(new File(pathname), true);
FileChannel channel = os.getChannel();
FileLock lock = channel.tryLock();
if (lock != null) {
ByteBuffer bytes = ByteBuffer.wrap(content.getBytes());
channel.write(bytes);
lock.release();
}
channel.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And new two thread with instances of the class:
String pathname = "/home/sjtu123/test.arff";
TrainSetBuildTask task1 = new TrainSetBuildTask(pathname);
Thread t1 = new Thread(task1);
TrainSetBuildTask task2 = new TrainSetBuildTask(pathname);
Thread t2 = new Thread(task2);
t1.start();
t2.start();
Then I get the error OverlappingFileLockException. I wonder why this happens since I just lock the file once in each thread? How can fix my code?
You cannot lock the same file more than once simultaneously. Either you need to use java lock objects to ensure only one thread tries to lock the file at a time, or otherwise coordinate the threads to wait until no other thread is locking.
From the manual:
File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With