• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

The Problem

When multiple threads access shared mutable data simultaneously, race conditions occur — two threads reading and writing the same variable can interleave in unpredictable ways, producing incorrect results. Without coordination, concurrent programs are unreliable.

Core Idea

Synchronization coordinates access to shared resources among threads. Java provides the synchronized keyword (which uses intrinsic locks/monitors), the volatile keyword (for visibility guarantees), and the java.util.concurrent.locks package (explicit Lock, ReentrantLock, ReadWriteLock).

How It Works

Every Java object has an intrinsic lock (monitor). When a thread enters a synchronized block or method, it acquires the object’s lock. Other threads attempting to enter any synchronized block on the same object block until the lock is released. synchronized guarantees both mutual exclusion and visibility (happens-before).

Visual Explanation

java_sync Counter Shared Object Counter { int value; } Lock Intrinsic Lock (Acquired by Thread 1) Counter->Lock T1Done Thread 1 releases lock Lock->T1Done released T1 Thread 1 synchronized(counter) {  counter.value++; } T1->Lock acquires T2 Thread 2 BLOCKED (waiting for lock) T2->Lock waiting... T1Done->T2 Thread 2 acquires lock

Semantic Network

semantic_synchronization THIS Synchronization THREAD Multithreading THIS--THREAD built from DEAD Deadlock THIS--DEAD builds into COLL Concurrent Collections THIS--COLL builds into PERF Performance THIS--PERF related

Key Properties

  • Intrinsic locks: Every Java object has a built-in monitor
  • synchronized methods: synchronized on an instance method locks this
  • synchronized blocks: More granular — specify the lock object explicitly
  • volatile: Guarantees visibility (reads see latest write) but not atomicity

Connections

Edge Cases & Gotchas

  • Double-checked locking: Famous bug pattern — volatile fixes it in Java 5+
  • Synchronized is reentrant: The same thread can acquire the same lock multiple times without blocking
  • Performance cost: Synchronized blocks have overhead — use for the smallest scope needed
  • Lock starvation: Low-priority threads may never acquire a contended lock