Search code examples
javalinuxlockingfile-locking

Java Filelock to prevent multiple writes by multiple JVM processes not working


I was learning FileOperations, and was writing a program to implement FileLocking on a linux machine.

  • The purpose of this program is, if multiple people invoke the program, the instance should aquire a file lock (Something similar to flock on a linux system).

  • I tried whether my program is working, by running the class file from two different terminal. However, it is returning true each time, thatis, even with the first process running and not releasing the lock, the second process is able to aquire the lock.

My code is

    public boolean getLock() throws FileNotFoundException, IOException{ 
    File lockFile = new File(conf_file);
    System.out.println("Attempting to aquire"
            + " exclusive lock on " + conf_file);
    RandomAccessFile f = new RandomAccessFile(lockFile, "rw");
    FileChannel channel = f.getChannel();
    FileLock lock;
    lock = channel.lock();
    if(lock != null && lock.isValid()){
        f.close();
        return true;
    }
    else{
        f.close();
        return false;
    }
}

What am I doing wrong here?


Solution

  • Remove the f.close() method and it should work. To remove the warning in your comment, declare those variables as instance variables and do an f.close in probably another method like removeLock().