Can synchronized lock a local variable? A Java multithreading demonstration
This article explains why the synchronized keyword cannot lock local variables in Java, demonstrates the behavior with multithreaded code examples, and shows that only class member variables can be effectively synchronized to control concurrent access.
The article investigates whether the synchronized keyword can lock a local variable in Java, concluding that it cannot because local variables reside on each thread's stack and are thread‑private.
Two Java programs are presented. The first creates two threads that both call demo2.testSync() , where a local String str = new String("test") is used as the lock object inside the synchronized block. Debugging shows both threads can enter the block simultaneously, indicating the lock on the local variable has no effect.
package com.sample.core.multithread; public class MultiThreadDemo { public static void main(String[] args) { MultiThreadDemo demo2 = new MultiThreadDemo(); Thread t1 = new Thread(() -> demo2.testSync()); Thread t2 = new Thread(() -> demo2.testSync()); t1.start(); t2.start(); } private int count = 0; public void testSync() { String str = new String("test"); synchronized (str) { for (int i = 0; i < 10; i++) { count++; } } } }
When the same code is modified to make str a class member variable instead of a local one, debugging shows that while one thread holds the lock (state RUNNING), the other thread is blocked (state MONITOR) until the lock is released.
package com.sample.core.multithread; public class MultiThreadDemo { public static void main(String[] args) { MultiThreadDemo demo2 = new MultiThreadDemo(); Thread t1 = new Thread(() -> demo2.testSync()); Thread t2 = new Thread(() -> demo2.testSync()); t1.start(); t2.start(); } private int count = 0; String str = new String("test"); public void testSync() { synchronized (str) { for (int i = 0; i < 10; i++) { count++; } } } }
The experiments confirm that synchronizing on a local variable does not provide mutual exclusion, whereas synchronizing on a shared member variable does, which is the correct way to protect critical sections in multithreaded Java programs.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
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.