Intrinsic Locks

Explicit Locks

  • package: java.util.concurrency.locks
  • Lock objects also support a wait/notify mechanism, through their associated Conditionobjects
  • The biggest advantage of Lock objects over implicit locks is their ability to back out of an attempt to acquire a lock.
  • The tryLock method backs out if the lock is not available immediately or before a timeout expires
  • The lockInterruptibly method backs out if another thread sends an interrupt before the lock is acquired
  • Examples:
    • ReentrantLock — interface: Lock
    • ReentrantReadWriteLock — interface: ReadWriteLock

General implementation pattern

  • You should not call lock method inside try because it may cause an unchecked exception to be thrown and if lock was actually not done then unlock will fail as well
Lock lock = ...; // your lock
lock.lock();
try {
    // do something
} catch (Exception e) {
    // handle the exception
} finally {
    lock.unlock();
}

Reentrant Lock

  • provides advanced features compared to intrinsic locking
public interface Lock {
    /**
     * Acquires the lock.
     */
    void lock();
 
    /**
     * Releases the lock.
     */
    void unlock();
    
    /**
     * other methods
     */
}

ReentrantReadWriteLock

  • Provides separate locking to reader and writer
public interface ReadWriteLock {
    Lock readLock(); // for reading
    Lock writeLock(); // for writing
}

Mutex

  • There is no such class in java
  • Mutex locks are the one which can be owned by at most one thread
  • https://www.baeldung.com/java-mutex
  • Mutex can be implemented in Java using:
    • synchronized block/method
    • ReentrantLock
    • Binary Semaphore