Class AutoCloseableReentrantLock

  • public class AutoCloseableReentrantLock
    extends Object
    A ReentrantLock lock that can be unlocked using an AutoCloseable. This allows for easy locking of resources, using a specific class as a namespace. Typical usage:
         try (final AutoCloseableReentrantLock.AutoCloseableLock ignored = new AutoCloseableReentrantLock(Clazz.class, user.getUsername()).lock()) {

    This essentially has the same effect as:

         synchronised ((Clazz.class.getName() + user.getUsername()).intern()) {

    but has advantages in that the current status of the lock can interrogated, the lock can be acquired interruptibly, etc.

    • Constructor Detail

      • AutoCloseableReentrantLock

        public AutoCloseableReentrantLock​(Class clazz,
                                          String resource)
        Create a class and resource specific lock. If another thread has not closed another AutoCloseableReentrantLock with the same class and resource then this will block until it is closed.
        clazz - The class for which the lock should be created.
        resource - The resource for which the lock should be created.