Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

synchronized — monitor locking

synchronized — monitor locking: synchronized acquires an object monitor before entering a block or method and releases it on every normal or abrupt exit.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

synchronized

synchronized acquires an object monitor before entering a block or method and releases it on every normal or abrupt exit.

Guard every operation on one shared invariant with the same private lock; an instance method locks this, while a static method locks the Class object.

A monitor is reentrant but offers no fairness guarantee; locking a public, interned, or replaceable object risks foreign synchronization or different locks.

A monitor unlock happens-before a subsequent lock of the same monitor; wait/notify require ownership. Literal synchronized(null) is a compile-time error, while a reference-typed expression that evaluates to null causes NPE.

Two threads perform 1,000 monitor-protected increments each, producing exactly 2000; true confirms ownership of counter’s monitor inside the block.

Examples

public class Main {
    static final class Counter {
        private int value;
        synchronized void increment() { value++; }
        synchronized int value() { return value; }
    }

    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Runnable work = () -> {
            for (int i = 0; i < 1_000; i++) counter.increment();
        };
        Thread first = new Thread(work);
        Thread second = new Thread(work);
        first.start();
        second.start();
        first.join();
        second.join();
        System.out.println(counter.value());
        synchronized (counter) {
            System.out.println(Thread.holdsLock(counter));
        }
    }
}

Result

2000
true

Two threads perform 1,000 monitor-protected increments each, producing exactly 2000; true confirms ownership of counter’s monitor inside the block.

Sources