Class NamedSimpleReentrantLock<T>

  • Type Parameters:
    T - the name type, required to be effectively immutable where T.hashCode() and T.equals() is concerned
    All Implemented Interfaces:
    Serializable, Lock

    public final class NamedSimpleReentrantLock<T>
    extends ReentrantLock
    A ReentrantLock which has a name and provides simplified locking operations.
    Author:
    Robert Varga
    See Also:
    Serialized Form
    • Constructor Detail

      • NamedSimpleReentrantLock

        public NamedSimpleReentrantLock​(T name)
    • Method Detail

      • getName

        public T getName()
      • tryAcquire

        public NamedSimpleReentrantLock.AcquireResult tryAcquire​(long timeout,
                                                                 TimeUnit unit)
        Tries to acquire the lock for the given key if it is not held by another thread within the given waiting time. See ReentrantLock.tryLock(long, TimeUnit) for more details.

        Example of use::

             NamedSimpleReentrantLockslt;?> lock;
        
             try (AcquireResult acq = lock.tryAcquire(1, TimeUnit.SECONDS)) {
                 // maybe locked region, not safe
        
                 if (acq.wasAcquired()) {
                     // locked region
                 } else {
                     // unlocked region
                 }
             });
        
             // lock released
         
        Parameters:
        timeout - the time to wait for the lock
        unit - the time unit of the timeout argument
        Returns:
        lock operation result. If the lock was free and was acquired by the current thread, NamedSimpleReentrantLock.AcquireResult.wasAcquired() will return true. If it reports false, the locking attempt has failed, either due to lock time expiring or the thread being interrupted while waiting.
      • tryAcquire

        public NamedSimpleReentrantLock.AcquireResult tryAcquire()
        Acquires the lock for the given key only if it is not held by another thread at the time of invocation. See ReentrantLock.tryLock() for more details.

        Example of use::

             NamedSimpleReentrantLock<?> lock;
        
             try (AcquireResult acq = locks.tryAcquire()) {
                 // maybe locked region
        
                 if (acq.wasAcquired()) {
                     // locked region
                 } else {
                     // unlocked region
                 }
             });
        
             // lock released
         
        Returns:
        lock operation result. If the lock was free and was acquired by the current thread, NamedSimpleReentrantLock.AcquireResult.wasAcquired() will return true. If it reports false, the locking attempt has failed,because another thread is currently holding the lock.