Class ReentrantFileLock

java.lang.Object
java.util.concurrent.locks.ReentrantLock
org.droolsassert.util.ReentrantFileLock
All Implemented Interfaces:
Serializable, Lock

public class ReentrantFileLock extends ReentrantLock
Combines ReentrantLock with FileLock
Suitable to synchronize threads from different VMs via file system.
As per documentation, file locks are held on behalf of the entire Java virtual machine.
Thus in most cases your ReentrantFileLock should be static to have single JVM instance of the lock object correspond to file lock for the entire JVM.
But it should not be an error to have several exclusive locks on JVM level correspond to single file lock id when you have valid technical usecase to do so.

Inner logic is fairly simple and imply acquiring first java ReentrantLock (fairness option belong here) and, when succeeded, continue further with acquiring file lock.
Release logic behaves in the opposite order.

ReentrantLock is reentrant, meaning the same thread can re-acquire the same lock again (lock held count get incremented).
The same logic implemented for the file lock, meaning any ReentrantFileLock(s) can re-acquire the same lock id on the file running within the same JVM (file lock held count get incremented implying no interaction with file system).
You can also synchronize on resources which are files on file system, like configuration files etc. Files will be locked for write though.

Consider Initialization-on-demand holder idiom for lazy loading

 private static final ReentrantFileLockFactory fileLockFactory = newReentrantFileLockFactory("target/droolsassert/lock");
 private static final ReentrantFileLock consolidatedReportLock = fileLockFactory.newLock(ActivationReportBuilder.class.getName());
 
 
 consolidatedReportLock.lock();
 try {
   ...
 } finally {
   consolidatedReportLock.unlock();
 }
 
See Also: