Language syntax

Synchronized monitor

Acquire the selected monitor for the block, releasing it on exit.

Formal Syntax & Structure

java syntaxjava
synchronized (lock) { /* guarded operations */ }

Working Example

Example Snippetjava
import java.time.Duration;import java.util.concurrent.*;public class Main {    // Only finite tasks and timed coordination are used in these examples.    static void finish(Thread thread) throws InterruptedException {        try {            if (!thread.join(Duration.ofSeconds(3))) {                thread.interrupt();                if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop");                throw new AssertionError("worker timed out");            }        } catch (InterruptedException e) {            thread.interrupt();            throw e;        }    }    static void meet(CyclicBarrier barrier) {        try { barrier.await(3, TimeUnit.SECONDS); }        catch (InterruptedException e) {            Thread.currentThread().interrupt();            throw new AssertionError("unexpected cancellation", e);        } catch (BrokenBarrierException | TimeoutException e) { throw new AssertionError(e); }    }    static final class Account {        final int id; int balance;        Account(int id, int balance) { this.id = id; this.balance = balance; }    }    static void transfer(Account from, Account to, int units) {        if (from == to || from.id == to.id || units <= 0) throw new IllegalArgumentException();        Account first = from.id < to.id ? from : to;        Account second = first == from ? to : from;        synchronized (first) {            synchronized (second) {                if (from.balance < units) throw new IllegalArgumentException("insufficient balance");                int credit = Math.addExact(to.balance, units);                from.balance -= units;                to.balance = credit;            }        }    }    public static void main(String[] args) throws Exception {        Account left = new Account(1, 10); Account right = new Account(2, 10);        CyclicBarrier start = new CyclicBarrier(2);        Thread a = new Thread(() -> { meet(start); transfer(left, right, 3); });        Thread b = new Thread(() -> { meet(start); transfer(right, left, 2); });        a.start(); b.start();        try { finish(a); } finally { finish(b); }        System.out.println(left.balance + ":" + right.balance);    }}
Java Reference