A synchronized block locks a string or a boxed primitive, which other code may share

tx0/java:lock-on-valuedefaultwarningbug, concurrency

What it finds

synchronized (name) on a String or a boxed number locks an object that other code may hold too: string literals are shared across the whole program, and Integer.valueOf hands out the same cached box for small values. Unrelated code that happens to lock the same value then blocks this code, or deadlocks with it. A private final Object used only as a lock cannot be shared that way.

From the rule's source, lock_on_value.rs.

Example from the rule's tests
class Registry {  private final String name = "registry";  private Integer count = 0;  private final Object lock = new Object();   void add() {    synchronized (name) {tx0 reports: name is a string, which other code may lock too      count++;    }    synchronized (count) {tx0 reports: count is a boxed value      count++;    }    synchronized ("global") {tx0 reports: is a string      count++;    }    synchronized (lock) {      count++;    }  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/java:lock-on-value" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:lock-on-value] reason="..."

tx0 explain tx0/java:lock-on-value shows the same in the terminal. Found a false positive? Report it.