Can Synchronizing on a Local Variable in Java Actually Acquire a Lock?

This article revisits a recent poll on MySQL field length, then presents a Java code example that uses the synchronized keyword on a locally created String variable, asking readers to determine whether this approach truly provides locking, and invites discussion on Java concurrency semantics.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Can Synchronizing on a Local Variable in Java Actually Acquire a Lock?

Welcome to the "Internet Full-Stack Architecture" WeChat public account. The previous poll discussed the meaning of the number in MySQL integer type definitions such as int(2), clarifying that the number does not limit the stored value length but only affects display in some consoles.

In the current poll, the focus shifts to Java concurrency. The synchronized keyword is commonly used to lock code blocks or methods, and a code snippet is provided where synchronization is applied to a locally created String object.

private int count = 0;
public void testSync() {
    String str = new String("test");
    synchronized (str) {
        for (int i = 0; i < 10; i++) {
            count++;
        }
    }
}

The question posed to readers is whether this code truly acquires a lock, considering that the lock object is a local variable that is not shared across threads.

Readers are invited to share their answers and insights.

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.

Javacode-example
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

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.