Interface NamedLock

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

    public interface NamedLock
    extends java.lang.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 Detail

      • name

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

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

        boolean lockExclusively​(long time,
                                java.util.concurrent.TimeUnit unit)
                         throws java.lang.InterruptedException
        Tries to lock exclusively, may block for given time. If successful, returns true.
        Throws:
        java.lang.InterruptedException
      • 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 java.lang.AutoCloseable