Locks in Java
Lock types, custom locks, Condition, and caching with read-write locks.
4 posts · In reading order
Locks in Java (Part 1): Lock Categories
Focusing on the object header’s Mark Word, this article explains acquisition, contention, release, and promotion of biased, lightweight, and heavyweight locks. JOL examples inspect lock flags before and after synchronized code, followed by discussion of spinning, blocking, and suitable use cases.
Locks in Java (Part 2): Implementing a Custom Lock
Introduces lock memory semantics and the use of AQS and the Lock interface to implement custom synchronization components, including an example that allows two concurrent threads. It also compares polling with wait/notify and discusses notification, competing for a lock again, and checking conditions.
Locks in Java (Part 3): Implementing Wait and Notify with Condition
Explains how to combine Lock and Condition to make threads wait and notify one another, comparing await, signal, and signalAll with wait/notify. A ReentrantLock example illustrates thread coordination and the requirement to acquire the lock before waiting or notifying and release it afterward.
Locks in Java (Part 4): High-Performance Web Page Caching with a Read-Write Lock
Starting with Ehcache 2 web-caching source code, this article analyzes the role of ReentrantReadWriteLock in concurrent cache loading. It then discusses an Ehcache 3 migration and how a custom Filter, cache keys, and a read-write lock cooperate to handle concurrent requests for the same page.