Interface NamedLock

All Superinterfaces:
AutoCloseable
All Known Implementing Classes:
AdaptedSemaphoreNamedLock, FileLockNamedLock, NamedLockSupport, NoopNamedLockFactory.NoopNamedLock, ReadWriteLockNamedLock

public interface NamedLock extends AutoCloseable
A named lock, functionally similar to existing JVM and other implementations. Must support boxing (reentrancy), but no lock upgrade is supported. The lock instance obtained from lock factory must be treated as a resource, best in try-with-resource block. Usual pattern to use this lock:
   try (NamedLock lock = factory.getLock("resourceName")) {
     if (lock.lockExclusively(10L, Timeunit.SECONDS)) {
       try {
         ... exclusive access to "resourceName" resource gained here
       }
       finally {
         lock.unlock();
       }
     }
     else {
       ... failed to gain access within specified time, handle it
     }
   }
 
  • Method Details

    • name

      String name()
      Returns this instance name, never null
    • lockShared

      boolean lockShared(long time, TimeUnit unit) throws InterruptedException
      Tries to lock shared, may block for given time. If successful, returns true.
      Throws:
      InterruptedException
    • lockExclusively

      boolean lockExclusively(long time, TimeUnit unit) throws InterruptedException
      Tries to lock exclusively, may block for given time. If successful, returns true.
      Throws:
      InterruptedException
    • unlock

      void unlock()
      Unlocks the lock, must be invoked by caller after one of the lockShared(long, TimeUnit) or lockExclusively(long, TimeUnit).
    • close

      void close()
      Closes the lock resource. Lock MUST be unlocked using unlock() in case any locking happened on it. After invoking this method, the lock instance MUST NOT be used anymore. If lock for same name needed, a new instance should be obtained from factory using NamedLockFactory.getLock(String). Ideally, instances are to be used within try-with-resource blocks, so calling this method directly is not really needed, nor advised.
      Specified by:
      close in interface AutoCloseable