Lock mechanism using Files on Java

Suppose the following scenario,

We have a process that can be executed from multiple places, even simultaneously, and a resource that is shared by said executions (it can be a file, a folder, a URL, a process, etc.).

We need to make sure that while this resource is being used, it is not modified, or that while we are modifying it, it is not used by other processes.

Let’s take as an example, we have a process that reads the content (files, folders) of a path and executes some logic. This process can be executed simultaneously 0 or more times. However, the content of this path can change from time to time: deleted files, added folders, or even modify the content of one or more files.

So we want to implement a locking mechanism that allows me exclusive use of the file for writing, and at the same time shared use while reading. We will do this using the Java NIO library.

Let’s do it

We will create a file, this can be located wherever you like, in this case we will place it in the root of the directory that we have as a resource. And we will call this file as .lock. We do not have to worry about the content of said file, we will only use the Java NIO options on this file to enable the locking mechanism.

Read LOCK

With the following code we can apply a Read Lock on a file:

Path lockFilePath = Paths.get("/my/path/.lock");
try (var channel = FileChannel.open(lockFilePath, StandardOpenOption.READ, StandardOpenOption.CREATE);
    FileLock lock = channel.lock(0, Long.MAX_VALUE, true)) {
   //Your logic here
}
  • We use the lock method of the FileChannel of our .lock file.
  • The StandardOpenOption.READ option indicates that we are accessing in read mode, which allows other reading processes to also use the file simultaneously.
  • The StandardOpenOption.CREATE option creates the .lock file for us if it does not exist (very first usage)

Write LOCK

With the following code we can apply a Write Lock on a file:

Path lockFilePath = Paths.get("/my/path/.lock");
try (var channel = FileChannel.open(lockFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
    FileLock lock = channel.lock(0, Long.MAX_VALUE, true)) {
   //Your logic here
}
  • We use the lock method of the FileChannel of our .lock file.
  • The StandardOpenOption.WRITE option indicates that we are accessing in write mode, which does not allow other read or write processes to be accessing at the same time.
  • The StandardOpenOption.CREATE option creates the .lock file for us if it does not exist (very first usage)

If for some reason we have a logic that is in write mode, and another reading or writing process tries to obtain a lock on the .lock file, that will not be possible. This process will wait until the initial writing process is finished, and only until that moment, it will continue.

Similarly, if there are one or more processes in read mode, and a writing process tries to lock the .lock file, this writing will wait until the reading processes finish .

Simplifying the code

Now that we understand the basics, we can create a class that helps us simplify that code, and make it more generic so that we can use it for multiple purposes.

public class {
 private final Path lockFilePath;
  
 public FileLockHelper(String path){
   lockFilePath = Paths.get(path);
 }
  
 public <T> T readLock(Executable<T> function) throws IOException {
    try (var channel = FileChannel.open(lockFilePath, StandardOpenOption.READ, StandardOpenOption.CREATE);
        FileLock lock = channel.lock()) {
      return function.execute();
    } 
  }
  
  public <T> T writeLock(Executable<T> function) throws IOException {
    try (var channel = FileChannel.open(lockFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        FileLock lock = channel.lock()) {
      return function.execute();
    } 
  }

  @FunctionalInterface
  public interface Executable<V> {
    V execute() throws IOException;
  }
}

We create a functional interface Executable to be used as a parameter in our methods, and then execute it as a lambda expression. In this way we can include any logic within the writeLock or readLock methods.

Finally, we can use the FileLockHelper this way.

FileLockHelper fileLockHelper = new FileLockHelper("/my/path/.lock"); 
fileLockHelper.writeLock(() -> {
  //Add my logic here
  return 1;
})
fileLockHelper.read(() -> {
  //Add my logic here
  return "String";
})  

Conclusions

This mechanism can be used for multiple purposes, not just the exercise that was presented in this article. Ensuring the integrity of our data is very important, especially when we have applications that concurrently access the same resource.

Applying locking mechanisms is not an easy task, but with a little imagination you can find simple alternatives that can help us for many scenarios, like this one we have presented. Hoping it will be helpful to many people.

References

Leave a Reply

Your email address will not be published. Required fields are marked *