Understanding Java's Synchronized Keyword and Lock Mechanism

Core Concepts

The synchronized keyword in Java uses lock mechanisms to achieve thread synchronization. It provides two key properties:

  • Mutual Exclusion: Only one thread can hold the object lock at any given time, ensuring atomic operations.
  • Visibility: Changes made to shared variables are visible to other threads acquiring the same lock.

Implementation Methods

Object Lock

Includes instance method locks (using 'this') and synchronized blocks (with custom lock objects):

class ThreadDemo implements Runnable {
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

    public static void main(String[] args) {
        ThreadDemo demo = new ThreadDemo();
        new Thread(demo).start();
        new Thread(demo).start();
    }

    public void run() {
        synchronized(lock1) {
            System.out.println(Thread.currentThread().getName() + " acquired lock1");
            try { Thread.sleep(1000); } catch (Exception e) {}
        }
        synchronized(lock2) {
            System.out.println(Thread.currentThread().getName() + " acquired lock2");
            try { Thread.sleep(1000); } catch (Exception e) {}
        }
    }
}

Class Lock

Applies to static methods or when locking on Class objects:

class StaticLockDemo implements Runnable {
    public static void main(String[] args) {
        new Thread(new StaticLockDemo()).start();
        new Thread(new StaticLockDemo()).start();
    }

    public void run() {
        staticMethod();
    }

    public static synchronized void staticMethod() {
        System.out.println(Thread.currentThread().getName() + " in static method");
        try { Thread.sleep(1000); } catch (Exception e) {}
    }
}

Implementation Mechanism

JVM uses monitor objects for synchronization. Each object has an associated monitor:

  • Threads enter monitor via monitorenter instruction
  • Threads exit monitor via monitorexit instruction
  • Monitor maintains entry lists and wait sets

Lock Optimizaton Techniques

Lock Coarsening

Combines multiple adjacent locks into a single larger lock:

void example() {
    synchronized(this) { operation1(); }
    synchronized(this) { operation2(); }
    // Optimized to:
    synchronized(this) {
        operation1();
        operation2();
    }
}

Lock Elimination

Removes unnecessary locks when JVM detects no actual contention:

String concatExample(String a, String b) {
    // No actual synchronization needed
    return a + b;
}

Lock Upgrade Process

Java's lock statees progress through:

  1. No lock
  2. Biased lock (favoring first acqiuring thread)
  3. Lightweight lock (using CAS operations)
  4. Heavyweight lock (full monitor)

Comparison with Lock Interface

Feature Synchronized Lock
Timeout No Yes
Interruptible No Yes
Multiple Conditions No Yes

Tags: java Synchronized thread-safety lock-mechanism Concurrency

Posted on Fri, 12 Jun 2026 16:25:50 +0000 by Lphp