Unlocking Java’s synchronized: When Does It Really Protect?
This article explores Java’s synchronized keyword in depth, covering its purpose, usage with object and class locks, seven multithreading scenarios, core principles like reentrancy and visibility, performance drawbacks, and best practices for choosing between synchronized and explicit Lock implementations.
Overview
Introduction: purpose, status, impact of not controlling concurrency
Usage: object lock and class lock
Seven multithreaded access scenarios
Properties: reentrancy, non‑interruptible
Principles: lock/unlock, reentrancy counter, visibility (JMM)
Drawbacks: low efficiency, inflexibility, unpredictable acquisition
How to choose between Lock and synchronized
1. Introduction
1.1 Purpose
Ensures that at most one thread executes the protected code at any moment, guaranteeing thread‑safety.
1.2 Position
synchronized is a Java keyword, natively supported.
Basic mutual‑exclusion primitive.
Foundational construct for concurrent programming.
1.3 Impact of not controlling concurrency
Example: two threads increment a shared variable a++ without synchronization; the result is nondeterministic and usually less than the expected value.
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++;
}
}
}Expected 20000, but repeated runs produce values such as 10108, 11526, 10736, …
2. Usage: Object lock and Class lock
2.1 Object lock
Code block form: manually specify lock object.
Method form: synchronized method locks on 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("start:" + Thread.currentThread().getName());
try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); }
System.out.println("end:" + Thread.currentThread().getName());
}
}
}2.2 Class lock
A class lock is the lock of the Class object; all instances share it.
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("start:" + Thread.currentThread().getName());
try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); }
System.out.println("end:" + Thread.currentThread().getName());
}
}3. Seven multithreaded access scenarios
Two threads access the same object's synchronized method.
Two threads access two objects' identical synchronized method.
Two threads access two objects' identical static synchronized method.
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 a small program; the output shows whether the threads run sequentially or concurrently.
4. Properties
4.1 Reentrancy
A thread that already holds a lock can acquire it again, preventing deadlock and allowing nested synchronized calls.
4.2 Non‑interruptible
If a thread is waiting for a lock, it can only block until the lock is released; it cannot be interrupted like a Lock can.
5. Principles
5.1 Lock/Unlock mechanism
Each object has a monitor; entering a synchronized block issues a monitorenter bytecode, exiting issues monitorexit. The JVM ensures only one thread holds the monitor at a time.
5.2 Reentrancy counter
The JVM tracks how many times the current thread has entered the monitor; the lock is released only when the counter reaches zero.
5.3 Visibility (JMM)
When a synchronized block exits, all writes to shared variables are flushed to main memory, guaranteeing that subsequent reads see the latest values.
“synchronized guarantees that after a thread releases the lock, the updated state is visible to other threads.”
6. Drawbacks
Low efficiency because lock acquisition and release are relatively heavy.
Cannot specify a timeout when trying to acquire a lock; threads may block indefinitely.
Cannot be interrupted while waiting for a lock.
Less flexible than explicit Lock implementations (e.g., read‑write locks).
Cannot predict whether lock acquisition will succeed.
7. Common questions
7.1 When to use Lock vs. synchronized ?
Prefer high‑level concurrency utilities from java.util.concurrent when they meet the requirement.
Use synchronized for simple mutual exclusion; it is concise and less error‑prone.
Switch to Lock only when you need features such as timed try‑lock, interruptible lock acquisition, or multiple condition variables.
8. Final summary
The JVM uses monitors to lock and unlock, ensuring that at any moment only one thread can execute the protected code, providing thread safety with reentrancy and non‑interruptibility.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
