Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does OverlappingFileLockException happen when locking a file?

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?

like image 492
jerry_sjtu Avatar asked Mar 28 '12 11:03

jerry_sjtu


1 Answers

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.

like image 116
Attila Avatar answered Oct 14 '22 01:10

Attila