Java learning pathSection 16

Synchronization Internals

Inspect the low-level JVM locking mechanisms and atomic primitives used for safe concurrency.

1

Monitor Locks

A monitor lock is the object-level synchronization primitive used by Java when a synchronized block or method is entered.

Each object can have an associated monitor that controls mutual exclusion.

Two threads compete for one monitor; its owner enters the critical section while contenders block. Unlock happens-before a subsequent lock of the same monitor, establishing memory visibility.
Monitor Locks
2

Intrinsic Locks

Intrinsic locks are the built-in Java mechanism used to guard critical sections of code.

They ensure that only one thread can execute a synchronized block on a given object at a time.

3

Synchronized Keyword

The synchronized keyword protects code by acquiring and releasing the monitor associated with an object or class.

This guarantees mutually exclusive access to critical sections and establishes memory visibility guarantees.

4

Object Monitor

The object monitor stores lock state, waiting threads, and ownership data for synchronized access.

This internal state is used by the JVM to manage contention and wake waiting threads.

5

Biased Locking (Legacy)

Biased locking allowed a lock to prefer a single thread repeatedly acquiring it without contention overhead.

This optimization was eventually reduced in importance as JVMs evolved and locking strategies improved.

6

Lightweight Locking

Lightweight locking reduces lock overhead when contention is low and the lock is not heavily contested.

It is intended to improve performance for uncontended synchronized code paths.

7

Heavyweight Locking

Heavyweight locking is used when contention is high or when the JVM needs to block waiting threads.

This is more expensive but safer and more scalable under sustained contention.

8

Lock Inflation

Lock inflation is the process of upgrading a lightweight or biased lock to a heavier monitor-based lock when contention rises.

This balances low overhead with correctness under multiple threads.

9

Lock Escalation

Lock escalation is the movement from low-overhead strategies to more expensive locks as workload concurrency increases.

It helps the JVM adapt to performance needs without sacrificing correctness.

10

CAS (Compare-And-Swap)

CAS performs an atomic compare-and-set operation, allowing algorithms to update values without traditional locking.

This is a core primitive for lock-free data structures and concurrent libraries.

11

Unsafe Class

The Unsafe class exposes low-level memory and concurrency operations that are not part of the standard Java API.

It is powerful but bypasses many safety guarantees, so it must be used with extreme caution.

12

VarHandle

VarHandle provides a safer and more structured API for atomic access to variables and array elements.

It is often preferred over Unsafe for modern concurrency code when low-level access is required.