Synchronization On String Literal

ID

java.sync_on_string

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:412, reliability

Description

Reports synchronized(…​) statements whose lock expression is a String literal.

Rationale

The JVM interns string literals, so any two "foo" references in any two classes yield the same String object. Locking on a literal therefore shares a monitor with every other piece of code in the application (and any loaded library) that happens to pick the same text — a silent source of deadlock and contention that doesn’t show up in review.

// Bad — this monitor is shared with every other class that writes synchronized("LOCK")
synchronized ("LOCK") {
    doWork();
}

Remediation

Synchronize on a private, purpose-built lock object:

// Good
private final Object lock = new Object();

public void work() {
    synchronized (lock) {
        doWork();
    }
}

Or, for class-scoped locking, use a private static final Object holder. Never reuse an interned string, boxed primitive (Boolean.TRUE), or a public object reachable from other modules.