Class CycleDetectingLockFactory.WithExplicitOrdering<E extends Enum<E>>

  • Type Parameters:
    E - The Enum type representing the explicit lock ordering.
    Enclosing class:
    CycleDetectingLockFactory

    @Beta
    public static final class CycleDetectingLockFactory.WithExplicitOrdering<E extends Enum<E>>
    extends CycleDetectingLockFactory
    A CycleDetectingLockFactory.WithExplicitOrdering provides the additional enforcement of an application-specified ordering of lock acquisitions. The application defines the allowed ordering with an Enum whose values each correspond to a lock type. The order in which the values are declared dictates the allowed order of lock acquisition. In other words, locks corresponding to smaller values of Enum.ordinal() should only be acquired before locks with larger ordinals. Example:
    
     enum MyLockOrder {
       FIRST, SECOND, THIRD;
     }
    
     CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory =
       CycleDetectingLockFactory.newInstanceWithExplicitOrdering(Policies.THROW);
    
     Lock lock1 = factory.newReentrantLock(MyLockOrder.FIRST);
     Lock lock2 = factory.newReentrantLock(MyLockOrder.SECOND);
     Lock lock3 = factory.newReentrantLock(MyLockOrder.THIRD);
    
     lock1.lock();
     lock3.lock();
     lock2.lock();  // will throw an IllegalStateException
     

    As with all locks created by instances of CycleDetectingLockFactory explicitly ordered locks participate in general cycle detection with all other cycle detecting locks, and a lock's behavior when detecting a cyclic lock acquisition is defined by the Policy of the factory that created it.

    Note, however, that although multiple locks can be created for a given Enum value, whether it be through separate factory instances or through multiple calls to the same factory, attempting to acquire multiple locks with the same Enum value (within the same thread) will result in an IllegalStateException regardless of the factory's policy. For example:

    
     CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory1 =
       CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...);
     CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory2 =
       CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...);
    
     Lock lockA = factory1.newReentrantLock(MyLockOrder.FIRST);
     Lock lockB = factory1.newReentrantLock(MyLockOrder.FIRST);
     Lock lockC = factory2.newReentrantLock(MyLockOrder.FIRST);
    
     lockA.lock();
    
     lockB.lock();  // will throw an IllegalStateException
     lockC.lock();  // will throw an IllegalStateException
    
     lockA.lock();  // reentrant acquisition is okay
     

    It is the responsibility of the application to ensure that multiple lock instances with the same rank are never acquired in the same thread.

    Since:
    13.0