Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Java synchronized Deep Dive: Lock Mechanics, Upgrades, Deadlocks & Production Checklists

This article analyzes three real-world concurrency accidents to explain synchronized's lock essence, Mark Word upgrade mechanism, proper lock object selection, wait/notify cooperation, deadlock prevention via global ordering, and provides production-ready templates including a three-question design checklist, four code patterns, and an eight-point code review checklist.

The article opens with three production accidents that illustrate the real risks of synchronized misuse:

Accident 1 (Deadlock): A payment service locked transfer-out and transfer-in accounts in parameter order. During a marketing event, A→B and B→A transfers created a circular wait: thread 1 held account 1 waiting for account 2, thread 2 held account 2 waiting for account 1. Eight threads deadlocked, P99 latency spiked from 80ms to gateway timeout. The fix was a global utility that sorts locks by account ID before acquisition.

Accident 2 (Coarse-grained lock): An inventory service wrapped the entire deduction method in synchronized, including inventory check, counter decrement, writing a ledger, and sending MQ (85% of latency). QPS dropped from 3200 to 210. Shrinking the critical section to only the check-and-decrement lines restored QPS to 2900.

Accident 3 (Wrong lock object): An idempotency check used synchronized (Long.valueOf(orderId)). For IDs outside the -128..127 cache, each call returns a new Long object, so two threads locked different objects and mutual exclusion failed. The same order was booked twice, causing ¥47,000 loss.

I. Lock Essence: You Lock an Object, Not Code

synchronized

never locks code; it locks an object. synchronized(this) means "acquire the lock on this object, then execute the block." Two threads calling the same synchronized method on different instances do not block each other because they lock different objects. The lock lives in the object header's Mark Word (64 bits on 64-bit HotSpot): 31 bits for identity hashcode, 4 bits for GC age, 1 bit for bias flag, 2 bits for lock state. When locked, these bits are repurposed to store biased thread ID, stack lock record pointer, or monitor pointer. The entire lock state machine lives in these 64 bits. This also explains why an object that has computed its identity hashcode can never enter biased state: the bits are already occupied.

In heavyweight state, the object header points to a C++ ObjectMonitor with fields: _owner (current holder), _EntryList (blocked queue), _WaitSet (threads that called wait()), _recursions (reentry count). Every Java object has a monitor; wait/notify operate on its _WaitSet. This makes it logical that wait must be called inside synchronized: you must hold the monitor to manipulate its wait set.

II. Lock Upgrade: Performance Anxiety Is Overblown

" synchronized is slow" is a JDK 5 myth. JDK 6 introduced adaptive upgrade: Unlocked → Biased → Lightweight → Heavyweight , upgrade-only (reset only at GC). Most real-world scenarios — single-threaded repeated access or alternating access without true contention — resolve via a few CAS operations on the Mark Word, never entering the kernel or parking threads.

Four states in detail:

Unlocked (01): New object, Mark Word holds hashcode + age.

Biased (01 + biased=1): First thread's ID recorded; subsequent entries by same thread need only a reference comparison, no CAS. Cost: any second thread attempting acquisition triggers revocation and upgrade.

Lightweight (00): Thread allocates a Lock Record in its own stack frame, CASes Mark Word to point to it. On failure, adaptive spinning (dynamic spin count based on past success) retries briefly before upgrading.

Heavyweight (10): Inflates to ObjectMonitor; contending threads park in _EntryList — two kernel context switches per park/unpark, microsecond overhead, major P99 jitter source.

Two critical updates: (1) Since JDK 15 (JEP 374) biased locking is disabled by default and removed in JDK 18 — modern thread-pooled apps see more revocation cost than benefit, so the path becomes unlocked → lightweight directly. (2) Upgrade is irreversible: once an object becomes heavyweight under high contention, it stays heavyweight. Hence hot objects must avoid high-contention access — the mechanical basis for the striping/partitioning strategies in Section V.

Lightweight lock records live in the thread's stack frame; acquire/release are pure user-mode pointer swaps. Adaptive spinning bets that contention ends quickly; if the bet loses once, it upgrades to stop wasting CPU.

III. Three Syntaxes & Lock Object Selection: What You Lock Matters More Than How Long

synchronized

has three forms, each locking a different object:

Instance method: synchronized void pay() locks this — protects per-instance state.

Static method: static synchronized void pay() locks the Class object — global JVM-wide lock, large blast radius, avoid unless protecting static fields.

Code block: synchronized (obj) {…} locks the given object — most flexible, most dangerous because any object can be passed (including boxed values and string constants).

Three classic wrong patterns from Accident 3: new Long(id) / Long.valueOf(id) — boxing may return a new object each time (outside -128..127), so threads lock different objects; mutual exclusion fails. Even within the cache, all code locking Integer.valueOf(42) shares one global lock, serializing unrelated work and risking deadlock.

String constant "ORDER" — interned in constant pool, globally shared; locking it serializes every unrelated use of that literal across the JVM.

Only correct pattern: final Object lock = new Object() — dedicated, immutable, semantically clear private lock object. Name it after the resource it guards ( accountLock, stockLock).

After choosing the right object, the second throughput lever is lock scope. Rule: Critical section contains only shared-state reads/writes; RPC, DB, logging, MQ all move outside. Accident 2 spent 85% of method time on I/O inside the lock. Hidden trap: lock scope must align with protection scope — check and write must be under the same lock to avoid check-then-act races; conversely, unrelated state must not be pulled into the same lock, causing Accident 2's serialization.

Lock design = enumerate shared state, then assign each piece a unique guarding lock. The two tables must match.

Important nuance: static synchronized and synchronized(this) do not mutually exclude — they lock different objects ( Class vs instance). If both touch the same static field, the lock is ineffective. Guarding lock must match the ownership of the protected state.

IV. wait/notify: Cooperation & Deadlock as Two Sides of One Coin

wait/notify

are the cooperation primitives inside the synchronized ecosystem. Semantics: holder finds condition unsatisfied, releases lock and waits; another thread prepares condition and wakes it. Four hard rules:

Must be called inside synchronized block (operates on monitor's _WaitSet; otherwise IllegalMonitorStateException). wait() releases the lock (otherwise no other thread can enter to change the condition).

After wakeup, thread must re-acquire the lock (notify moves thread from _WaitSet to _EntryList; only after winning the lock does it return from wait()).

Condition must be re-checked in a while loop — notifyAll wakes all waiters but only one can consume the condition; late wakers may find it gone (spurious wakeup in engineering terms).

Accident 1's transfer deadlock is a textbook case: mutual exclusion (account locks), hold-and-wait (hold from wait for to), no preemption ( synchronized lacks timeout/interrupt), circular wait (A waits for B, B waits for A). Breaking any condition prevents deadlock. Breaking circular wait via global ordering (sort by account ID) is most common; breaking no-preemption uses JUC tryLock with timeout (covered in next article). synchronized only has the ordering defense — the sole hard reason to consider JUC in multi-lock scenarios.

Deadlock detection triad: jstack prints "Found one deadlock" with waiting stacks. arthas thread -b one-liner to locate blocking root (internally calls ThreadMXBean.findDeadlockedThreads).

Monitoring: scheduled task calling findDeadlockedThreads, immediate P1 alert — deadlocks never self-heal; rising stuck thread count is the signal. Section 5.3 provides copy-paste detection code.

Correct defense = "pre-agreed ordering + continuous online detection" dual layer. Ordering blocks occurrence; detection catches leaks.

Engineering alternative view: For simple single-producer/single-consumer, Condition with Lock is equivalent to wait/notify (it's the API-fied monitor cooperation). API-fication adds explicit multi-condition, interruptible wait ( awaitNanos), fairness. Guidance: stay with synchronized + wait/notify if no multi-condition/timeout/fairness needs; migrate to Condition when needs exceed; step-wise, not jump to most complex tool.

V. Production Practice: Three Questions, Four Templates, Eight-Point Checklist

Before writing any synchronized, answer three questions:

Q1: What do I lock? — Dedicated final object, clear semantics; ban boxed values, string constants, cached objects.

Q2: How big is the critical section? — Only shared-state reads/writes; all I/O outside.

Q3: What is the acquisition order? — Multi-lock scenarios must have global consistent order or timeout fallback. If you can't answer, design is incomplete.

Four templates for high-frequency scenarios:

5.1 Fine-grained Account Lock: Striping Template (prevents Accident 1)

// Per-account lock striping (fine-grained lock entries)
public class AccountLocks {
    private final ConcurrentHashMap<Long, Object> locks = new ConcurrentHashMap<>();

    public Object lockOf(long id) {
        return locks.computeIfAbsent(id, k -> new Object());
    }
}

// Transfer: acquire two locks in ID-sorted order
public boolean transfer(long fromId, long toId, long amount) {
    Object first = lockOf(Math.min(fromId, toId));
    Object second = lockOf(Math.max(fromId, toId));
    synchronized (first) {
        synchronized (second) {
            return doTransfer(fromId, toId, amount);
        }
    }
}

Two design points: (1) computeIfAbsent lazily creates lock entries — memory scales with active accounts, not total; computeIfAbsent guarantees single creation per key, stable reference (vs Accident 3's new object each time). (2) Lock entries only grow — slow leak at hundreds of millions of accounts; switch to WeakHashMap or periodic cleanup of inactive entries. Math.min/max sorting is the global ordering discipline: all money-moving operations must route through this single utility; business code must never write synchronized(from){synchronized(to)}.

5.2 Global Ordering Utility: Encode Discipline in Code

// Global ordering lock utility (payment chain only)
public final class LockOrdering {
    private LockOrdering() {}

    public static void lockSorted(Object a, Object b) {
        Object first = System.identityHashCode(a) <= System.identityHashCode(b) ? a : b;
        // Real impl sorts by business key: e.g., account ID, see 5.1
        synchronized (first) {
            synchronized (b == first ? a : b) {
                // critical section executed by callback
            }
        }
    }
}

Skeleton for "ordering as a utility": production must sort by business key (account ID, order number — globally unique and comparable), not identityHashCode (collisions break ordering). Utility's value is enforcement: business code loses the ability to choose order; Accident 1's "parameter-order locking" disappears at code review. Combined with checklist item 3 "multi-lock has order?", discipline loop closes.

5.3 Deadlock Detection: 30-Second Online Safety Net

// Periodic deadlock detection (P1 alert)
@Scheduled(fixedDelay = 30_000)
public void detectDeadlock() {
    ThreadMXBean mx = ManagementFactory.getThreadMXBean();
    long[] ids = mx.findDeadlockedThreads();
    if (ids != null && ids.length > 0) {
        alert.fire("deadlock.found," + ids.length + " threads");
        for (long id : ids) {
            ThreadInfo info = mx.getThreadInfo(id);
            log.error("deadlock: {}", info);
        }
    }
}
findDeadlockedThreads

returns array of thread IDs forming a cycle — non-empty means deadlock has occurred. Covers both monitor deadlocks and JUC ownable-synchronizer deadlocks, better suited for continuous patrol than manual jstack. Two ops details: (1) Alert must include thread stacks ( getThreadInfo logged) so on-call doesn't need to SSH for jstack. (2) Deadlocks don't self-heal — post-alert action is locate locking code, fix order or add timeout, not just restart (same traffic pattern will reproduce).

Detection scope expansion: findDeadlockedThreads finds already-formed cycles. Another stealth class is "near-deadlock" — no cycle, but one thread holds a lock for ten minutes in a long-running batch job, starving all waiters. Deadlock detection misses this; need thread-pool monitoring and P99 divergence metrics from Article 1. Boundary: threads waiting for each other (detectable) vs threads waiting for slow code (only metrics catch) — lock health monitoring always needs two legs: deadlock detection + latency metrics.

5.4 wait/notify Correct Template: Bounded Buffer (prevents spurious wakeup)

// wait/notify standard pattern
public class BoundedBuffer {
    private final Object notFull = new Object();
    private final Object notEmpty = new Object();
    private final Object[] items = new Object[16];
    private int count, putIdx, takeIdx;

    public void put(Object x) throws InterruptedException {
        synchronized (notFull) {
            while (count == items.length) {
                notFull.wait(); // re-check
            }
            items[putIdx] = x;
            if (++putIdx == items.length) putIdx = 0;
            ++count;
        }
        synchronized (notEmpty) {
            notEmpty.notifyAll();
        }
    }
}

Template condenses four rules: (1) Two conditions, two locks ( notFull for producers, notEmpty for consumers — avoids notifying wrong object; single lock with multiple conditions is the most common wait/notify misuse). (2) while re-check prevents spurious wakeup. (3) notifyAll (only use notify if you are certain exactly one waiter exists; otherwise lost wakeup risk — thread stuck forever — far outweighs extra wakeup cost). (4) Update state before notify; reversed order creates a window where condition is true but no one knows. Production note: this example teaches mechanism — real bounded queues use ArrayBlockingQueue / LinkedBlockingQueue (Article 6), industrial implementations of this logic. Hand-written wait/notify is justified only for custom cooperation conditions, e.g., "wait until inventory refresh completes".

Eight-Point Code Review Checklist (One Veto Fails)

Lock object dedicated? (ban boxed/constant/cached)

Critical section small enough? (all I/O outside)

Multi-lock has global order? wait inside while? notifyAll used correctly (only notify if single waiter)?

Reentrancy accounted? (same thread re-entering same lock increments _recursions; won't self-deadlock but don't rely on it)

Any I/O accidentally inside lock?

Lock scope aligns with shared state? (no under-protection, no over-serialization)

Paste into code review template — lock bugs don't explode on your machine; they explode when three orgs' concurrent traffic hits simultaneously.

VI. Core Source Code: Four Key Implementations

1. monitorenter Bytecode

Compilation product of a synchronized block; note two exit paths:

// Bytecode view: sync block
public void pay() {
    synchronized (this) {
        balance -= 10;
    }
}
// Compilation output (excerpt):
// aload_0
// dup
// monitorenter <- acquire object lock
// ...balance decrement...
// monitorexit <- normal exit
// goto done
// exception table entry:
// monitorexit <- exceptional exit
// athrow <- rethrow exception

Key design: compiler emits two monitorexit instructions — one for normal path, one in exception table covering the critical section, followed by athrow to rethrow. Guarantees lock release on any exception — no "exception leaks lock". Cost: exception path also executes unlock (JVM level), negligible overhead. For synchronized methods, no monitorenter bytecode; relies on method's ACC_SYNCHRONIZED flag for implicit locking at call — same semantics, different implementation path.

2. ObjectMonitor::enter

Heavyweight lock acquisition path — shows where contention cost goes:

// ObjectMonitor::enter (simplified)
void ObjectMonitor::enter(Thread * self) {
    // 1. CAS for _owner: fast path
    if (Atomic::cmpxchg_ptr(self, &_owner, NULL) == NULL) {
        _recursions = 0;
        return;
    }
    // 2. Reentry: self is already owner
    if (owner == self) {
        _recursions++;
        return;
    }
    // 3. Slow path: spin a few rounds then
    //    park into _EntryList (kernel, microsecond cost)
}

Three paths map to three fates: (1) CAS succeeds — no contention or contention just ended, one atomic op gets lock, the daily " synchronized isn't slow" path. (2) Reentry — self is owner, just increment counter, zero extra contention cost. (3) Slow path — user-mode adaptive spin, then park into _EntryList, thereafter each park/unpark is a kernel switch. All performance delta comes from path 3 — so optimization essence is keeping threads in paths 1/2: shrink critical section to shorten hold time, stripe locks to reduce contender count. Swapping to ReentrantLock only changes slow-path implementation; paths 1/2 optimization logic unchanged.

3. Mark Word Lock State Cheat Sheet

Compresses Section II's state machine into a bit map:

// Mark Word lock states (64b)
// Unlocked: |unused:25|hashcode:31| |age:4|biased:0|01
// Biased:   |thread:54|epoch:2| |age:4|biased:1|01
// Lightweight: |ptr_to_lock_record:62|00
// Heavyweight: |ptr_to_monitor:62|10
// GC mark: |...|11 (unrelated to lock)
// Low 2 bits = lock flag; biased bit distinguishes unlocked vs biased; biased only default-enabled pre-JDK 15 (JEP374)

Two practical uses: (1) Diagnose lock state — jol (Java Object Layout) prints object header Mark Word bitmap, verifying which level your lock actually sits at (great for teaching and tuning). (2) Understand identity hashcode constraint — unlocked stores 31-bit hashcode; biased needs 54 bits for thread ID in same location — conflict. Once an object computes identity hashcode (calls Object.hashCode without override), it permanently loses biased eligibility. Lightweight/heavyweight simply replace the whole word with a 62-bit pointer, stashing hashcode in lock record or monitor — so hashcode only affects biased, not later levels.

4. wait JVM Semantics

Full action sequence behind the cooperation primitive:

// Object.wait -> JVM semantics (simplified)
// Precondition: must hold this object's monitor
// (else IllegalMonitorState)
// Step 1: current thread added to _WaitSet
// Step 2: fully exit monitor
// (all reentry levels released, so other
// threads can acquire lock and change condition)
// Step 3: park, wait for notify
// (timed version waits millis)
// Step 4: on wakeup, re-compete for lock
// (enter slow path), only after winning
// does wait() return and continue
// notify: moves one thread from _WaitSet
// to EntryList to compete

This sequence explains three overlooked details: (1) wait releases all reentry levels — nested synchronized calling wait releases outer locks too; wakeup re-acquires layer by layer. (2) Wakeup ≠ lock held — between notify and winning the lock, new contenders may sneak in and change the condition; while re-check is the only defense. (3) wait interrupt semantics — interrupted while waiting throws InterruptedException after re-acquiring lock; standard pattern must handle interrupt properly (restore flag or propagate).

Four pieces connected: bytecode defines lock boundaries, enter defines contention cost, Mark Word defines state machine, wait defines cooperation semantics — mechanism read, Section II's upgrade path now has source-code-level foundation.

VII. Seven Cost Accounts: synchronized's Real Bill

Upgrade Account. No-contention scenarios (vast majority) cost a few CAS ops, comparable to AtomicInteger</sub> — "<code>synchronized is slow" basically false in daily code. Only scenario that pays: high contention + long critical section. Don't preemptively swap locks for non-existent perf issues.

Contention Account. Once heavyweight, each failed acquire parks once, wakes once — two kernel switches at microseconds each, plus scheduler latency, P99 stretched directly. Observability: jstack BLOCKED queue length, monitoring P99 vs throughput divergence. Antidote: Section V's granularity & striping design, not lock swap.

Granularity Account. Coarse lock kills throughput (Accident 2: 3200→210); fine lock raises complexity & deadlock surface — sweet spot: critical section contains only shared-state reads/writes . Moving I/O out usually yields orders-of-magnitude gain: Accident 2's shrink brought QPS to 2900; no lock swap achieves that.

Lock Object Account. Dedicated final object costs zero; wrong object costs accident-level loss (Accident 3: ¥47k). Investment: one-time "shared state inventory + guarding lock map" design — prevents the most expensive accident class — highest ROI in the article, worth establishing in every project .

Ordering Account. Global ordering for multi-lock has implementation cost (utility, review gate), vs deadlock debugging cost (production fund-chain block, jstack analysis, fix deploy) — ordering discipline is one-time spend for permanent immunity . Section 5.2's utility turns discipline into code.

Monitoring Account. Deadlock detection every 30s, negligible cost; vs deadlock incident firefighting (restart + investigation half-day minimum) — Section 6.3's template is second high-ROI spend. Add jstack / arthas troubleshooting skills; total lock monitoring bill tiny.

Substitution Account. When worth switching to JUC: need timeout ( tryLock breaks deadlock), fairness (starvation prevention), read-write separation (read-heavy throughput), multi-condition cooperation ( Lock+Condition). If none of these four, synchronized remains default — substitution principle: swap for requirements, not for anxiety . Seven-account P&L: upgrade free, contention/granularity free via design, object/ordering/monitoring are small one-time investments, substitution pay-as-needed — synchronized 's total bill far cheaper than its reputation.

VIII. 20 Interview Questions (with Answers)

Key Q&A highlights:

Q1: Three syntaxes lock this, Class, specified object; instance lock and class lock do not mutually exclude.

Q2: Upgrade path: Unlocked(01) → Biased(01+biased, first thread records ID) → Lightweight(00, second thread triggers revocation, CAS+stack LockRecord) → Heavyweight(10, spin limit or third thread joins, inflates to ObjectMonitor blocking). Upgrade-only, GC may reset.

Q3: Biased deprecated in JDK 15 because benefit scenario (single-thread repeated access) rare in modern thread-pooled apps; revocation needs safepoint, cost > benefit. JEP 374 disables default in 15, removes in 18. Principle remains interview hot topic.

Q4: Adaptive spin because fixed spins can't match load: high success rate → contention brief, more spins pay off; high failure → contention fierce, spinning burns CPU. Adaptive adjusts based on last spin result — success increases spins, failure bails out and upgrades.

Q5: ObjectMonitor fields: _owner, _EntryList, _WaitSet, _cxq (contention entry list), _recursions. wait/notify operate on _WaitSet.

Q6: Identity hashcode (31 bits) vs biased thread ID (54 bits) share same Mark Word bits — no room. Once identityHashCode computed, biased forever disabled; lightweight/heavyweight stash hashcode elsewhere, unaffected.

Q7: synchronized = JVM keyword, auto-release (even on exception), non-interruptible, non-fair, single condition ( wait/notify); ReentrantLock = API, manual unlock (must finally), interruptible, optional fair, multiple Condition, tryLock timeout. Functional superset, but synchronized has no forget-unlock leak risk and JIT can eliminate/coarsen. Default synchronized, swap only for four hard needs.

Q8: wait implementation depends on monitor's _WaitSet: enqueue, release lock, wakeup then re-acquire — all require "currently holds this monitor". No lock → IllegalMonitorStateException. Not syntax limit, logical necessity — non-holder has no authority to command threads inside the door.

Q9: Wakeup ≠ condition satisfied: notifyAll wakes all but only one consumes; between notify and re-acquire condition may be consumed or rolled back (spurious wakeup). while re-check guarantees unsatisfied → continue wait; if checks once, guaranteed bug.

Q10: Use notify only if all waiters wait for same condition and each wakeup allows exactly one success; any uncertainty → notifyAll. Lost wakeup cost (thread stuck forever) >> extra wakeup overhead. Single-condition multi-waiter: notify risks waking wrong thread, forbidden.

Q11: Reentrancy via ObjectMonitor._recursions: enter sees owner is self → increment; exit decrements, releases only when zero. Same-thread reentry never self-deadlocks; basis for nested synchronized. Note wait releases all levels.

Q12: Yes, lock releases on exception. Compiler emits two monitorexit for blocks (normal + exception table), athrow rethrows. Methods use ACC_SYNCHRONIZED flag, JVM call protocol guarantees unlock on exception. vs ReentrantLock forget- finally risk — synchronized safety advantage.

Q13: Lock elimination: JIT escape analysis finds lock object cannot be accessed by other threads (e.g., local StringBuffer append), removes lock/unlock entirely. Typical win: local StringBuilder / StringBuffer synchronized appends fully eliminated. Precondition: lock object doesn't escape — shared object locks never eliminated.

Q14: Lock coarsening: adjacent repeated lock/unlock on same object (e.g., loop appends), JIT merges into one large lock region, reducing lock ops. Reminds us: granularity optimization has boundary — over-fine locks trigger JVM reverse coarsening; manual design should match shared-state boundaries.

Q15: Four deadlock conditions + break strategies: mutual exclusion, hold-and-wait, no-preemption, circular wait. Break any: break circular wait via global ordering (most common); break no-preemption via tryLock timeout + release; break hold-and-wait via one-shot all-resource request; mutual exclusion usually unbreakable. synchronized only has ordering defense (no timeout), multi-lock must establish ordering discipline.

Q16: Standard transfer fix: all transfers sort by account ID then lock — lock smaller ID first, then larger; circular wait impossible in graph theory. Encapsulate in unified utility ( lockSorted), forbid business code from deciding order; pair with ThreadMXBean.findDeadlockedThreads scheduled detection for dual safety. Ordering key must be globally unique, comparable, and consistent across entire call chain — half services by ID, half by timestamp = no ordering.

Q17: static synchronized and synchronized(this) do not mutually exclude — lock Class vs instance, two different locks. If both touch same static state, race occurs. Fix: unify lock object — static state uses Class lock or dedicated static lock object, instance state uses instance lock, ensure lock-to-state 1:1 mapping.

Q18: Can't use Integer / String /boxed types as locks: boxed values may be new objects each time → threads lock different objects, mutual exclusion fails; small ints & string constants use global cache/pool → locking one shared object serializes unrelated code and may deadlock with others. Correct: final Object dedicated private lock, name matches resource semantics.

Q19: synchronized cannot modify constructor — syntax forbids. During construction object not published to other threads, theoretically no concurrent access; if this escapes in constructor (register listener, start thread), problem is "this escape", fix is publish after construction (factory method, init callback), not locking constructor.

Q20: Online lock contention observability triad: jstack check target lock's BLOCKED queue (length = heavyweight contention intensity); arthas thread -b directly locate blocking source; JFR Java Monitor Blocked events rank locks by cumulative blocked time. Continuous monitoring: ThreadMXBean deadlock detection + thread count + P99 divergence metrics.

IX. One-Page Cheat Sheet

Ten takeaways: synchronized locks objects, not code; lock object = concurrency world's door number.

Lock object must be dedicated final, clear semantics — ban boxed values, string constants, cached objects.

Upgrade path: Unlocked → Biased (JDK 15 default deprecated) → Lightweight (CAS+spin) → Heavyweight (monitor+block), upgrade-only.

No contention = a few CAS — performance anxiety to upgrade mechanism, design anxiety to yourself.

Critical section only shared-state reads/writes; RPC/DB/MQ/logging all outside. wait trio: inside synchronized, while re-check, notifyAll wake.

Multi-lock must have global order: sort by business key, encode in utility, don't rely on discipline.

Deadlock four conditions, break one; synchronized only has ordering defense.

Deadlock detection: findDeadlockedThreads scheduled patrol, alert with stacks.

Swap to JUC for four hard reasons: timeout, fairness, read-write split, multi-condition — swap for needs, not anxiety.

Summary & Next Episode Preview

Starting from three accidents, walked the full chain "Lock Essence → Upgrade Mechanism → Usage & Lock Object → Cooperation & Deadlock → Production Practice": Mark Word's 64 bits carry the complete lock state machine; upgrade pushes no-contention cost to a few CAS; real risks are all design-layer — wrong lock object = loss accident, runaway critical section = throughput accident, missing order = deadlock accident. Production solution = three tables: shared state inventory, guarding lock map, acquisition order convention, plus "Three Questions + Eight-Point Checklist" two checklists — synchronized 's total bill is far cheaper than its reputation: 95% of perf issues exaggerated, 100% of design issues worth serious attention . Suggest baking three tables into team code review template: new code reviewed against eight-point checklist, legacy code audited by accident type on schedule — mechanisms are forgotten, checklists on the wall stay.

Next article " volatile & JMM" covers concurrency's visibility foundation: why volatile makes a variable cross-thread effective, how the eight happens-before rules guide daily coding, where DCL singleton goes wrong, and the division of labor between volatile and synchronized.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

synchronizedjava-concurrencywait-notifymark-wordobjectmonitorlock-upgradeproduction-patternsdeadlock-prevention

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion