How to create file lock in java?

When multiple threads work on a shared resource its quiet possible that one thread’s work is over written by another one if the shared resource is modified without a mutually exclusive lock. This can be solved by moving the code responsible for the state change of the shared resource into a synchronized method/block. What if the shared resource is outside the JVM? like a file and two program/process can change that file concurrently? In this kind of scenarios the file lock very useful. java.nio.channels package gives a class named FileLock to create a file lock in java, remember this implementation is platform dependent.

Let see a simple sample program to demonstrate the use of FileLock class.

Execute the above program from two shell and see the result. The first jvm instance would get a lock but the second jvm instance would exit without a file lock.

Console Output.

One thought on “How to create file lock in java?