Fundamentals 20 min read

Understanding Java synchronized: Overview, Usage, Scenarios, Principles, Drawbacks, and FAQs

This article provides a comprehensive guide to Java's synchronized keyword, covering its purpose, object and class lock usage, seven multithreading scenarios, reentrancy and non‑interruptibility properties, underlying lock and visibility mechanisms, performance drawbacks, and common questions with detailed code examples.

Top Architect
Top Architect
Top Architect
Understanding Java synchronized: Overview, Usage, Scenarios, Principles, Drawbacks, and FAQs

Overview

The synchronized keyword ensures that at most one thread executes a block of code at a time, providing concurrency safety.

Introduction: role, significance, and impact of not controlling concurrency.

Usage: object lock vs class lock.

Seven multithreading scenarios for synchronized methods.

Properties: reentrancy and non‑interruptibility.

Principles: lock/unlock mechanism, reentrancy counter, and Java Memory Model visibility.

Drawbacks: low efficiency, lack of flexibility, and inability to predict lock acquisition.

FAQs and best‑practice recommendations.

1. Introduction

Synchronized guarantees exclusive execution of a code block, preventing race conditions when multiple threads modify shared data.

1.1 Role

Ensures thread‑safe execution by allowing only one thread at a time.

1.2 Position

Synchronized is a Java keyword supported natively.

It is the most basic mutual exclusion mechanism.

It is a foundational tool in concurrent programming.

1.3 Impact of Not Controlling Concurrency

Example: two threads incrementing a shared counter without synchronization produce inconsistent results (e.g., expected 20000 but often less).

package cn.jsonshare.java.base.synchronizedtest;

public class SynchronizedTest1 implements Runnable {
    static SynchronizedTest1 st = new SynchronizedTest1();
    static int a = 0;
    public static void main(String[] args) throws Exception {
        Thread t1 = new Thread(st);
        Thread t2 = new Thread(st);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(a);
    }
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            a++;
        }
    }
}

Result values are typically far below 20000, demonstrating race conditions.

2. Usage: Object Lock and Class Lock

2.1 Object Lock

Two forms:

Code block with explicit lock object.

Method lock where synchronized modifies the method; the lock object defaults to this.

public class SynchronizedTest2 implements Runnable {
    static SynchronizedTest2 st = new SynchronizedTest2();
    public static void main(String[] args) throws Exception {
        Thread t1 = new Thread(st);
        Thread t2 = new Thread(st);
        t1.start();
        t2.start();
        while (t1.isAlive() || t2.isAlive()) {}
        System.out.println("run over");
    }
    @Override
    public void run() {
        synchronized (this) {
            System.out.println("开始执行:" + Thread.currentThread().getName());
            try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); }
            System.out.println("执行结束:" + Thread.currentThread().getName());
        }
    }
}

2.2 Class Lock

Class lock is essentially the lock on the Class object; only one thread can hold it at a time.

public class SynchronizedTest4 implements Runnable {
    static SynchronizedTest4 st1 = new SynchronizedTest4();
    static SynchronizedTest4 st2 = new SynchronizedTest4();
    public static void main(String[] args) throws Exception {
        Thread t1 = new Thread(st1);
        Thread t2 = new Thread(st2);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("run over");
    }
    @Override
    public void run() { method(); }
    public static synchronized void method() {
        System.out.println("开始执行:" + Thread.currentThread().getName());
        try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); }
        System.out.println("执行结束:" + Thread.currentThread().getName());
    }
}

3. Seven Multithreading Scenarios

Two threads access the same synchronized method of the same object.

Two threads access the same synchronized method of two different objects.

Two threads access the same static synchronized method of two objects.

One thread accesses a synchronized method while another accesses a non‑synchronized method of the same object.

Two threads access different synchronized methods of the same object.

Two threads access a static synchronized method and a non‑static synchronized method of the same object.

Does an exception thrown inside a synchronized method release the lock?

Each scenario is demonstrated with Java code and observed output, confirming the locking behavior described.

4. Properties

4.1 Reentrancy

A thread that already holds a lock can reacquire it, preventing deadlock and improving encapsulation. Java's synchronized and ReentrantLock are reentrant.

4.2 Non‑Interruptibility

Threads waiting for a synchronized lock cannot be interrupted; they must wait until the lock is released. In contrast, Lock implementations support interruption and timeout.

5. Principles

5.1 Lock/Unlock Mechanism

Compiled bytecode uses monitorenter and monitorexit instructions to acquire and release the monitor associated with the lock object.

// Simplified bytecode snippet
monitorenter
... // method body
monitorexit

5.2 Reentrancy Counter

The JVM tracks how many times a thread has acquired a particular lock; the lock is fully released only when the counter returns to zero.

5.3 Visibility (Java Memory Model)

Synchronized establishes a happens‑before relationship: actions before releasing the lock are flushed to main memory, and actions after acquiring the lock see the latest values.

When a synchronized block exits, all modifications to shared variables are written back to main memory, ensuring visibility to other threads.

6. Drawbacks

Low efficiency: limited release points and no timeout when acquiring.

Lack of flexibility: only one lock condition per object.

Cannot predict lock acquisition success, making it unsuitable for some high‑performance scenarios.

7. Frequently Asked Questions

7.1 When a synchronized method calls a non‑synchronized method, is it thread‑safe?

Yes, because the calling thread still holds the lock for the synchronized method, protecting the entire call chain.

public class SynchronizedScene8 {
    public static void main(String[] args) {
        new Thread(() -> method1()).start();
        new Thread(() -> method1()).start();
    }
    public static synchronized void method1() { method2(); }
    private static void method2() {
        System.out.println(Thread.currentThread().getName() + "进入非Synchronized方法");
        try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println(Thread.currentThread().getName() + "结束非Synchronized方法");
    }
}

Output shows serialized execution, confirming thread safety.

7.2 Choosing between Lock and synchronized

Prefer java.util.concurrent utilities when they meet requirements.

Use synchronized for simplicity and lower error risk.

Use Lock only when you need features like timeout, interruptibility, or multiple condition variables.

Conclusion

JVM uses monitors to lock and unlock, ensuring that only one thread executes the protected code at a time, providing thread safety with reentrancy and non‑interruptibility.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javalockingmultithreadingsynchronized
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.