A synchronized block locks a field that other code assigns, so threads can hold different locks
What it finds
synchronized (lock) protects nothing once another method runs lock = new Object(): threads that read the field before and after the assignment take different monitors and run the guarded code at the same time. A lock must stay the same object for as long as it guards anything, which the Java memory model's rules on monitors make necessary.
Reported is a synchronized block on a field of this file that is assigned outside its declaration, constructors, initializers and the methods that set up copies and deserialized objects: readObject, readResolve, readObjectNoData and clone.
From the rule's source, reassigned_lock_field.rs.
class Cache { private Object lock = new Object(); private Object guard; private final Object fixed = new Object(); private int size; Cache() { guard = new Object(); } void reset() { lock = new Object(); } void add() { synchronized (lock) {tx0 reports: lock is assigned elsewhere size++; } synchronized (guard) { size++; } synchronized (fixed) { size++; } }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:reassigned-lock-field" = "warning"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:reassigned-lock-field] reason="..."tx0 explain tx0/java:reassigned-lock-field shows the same in the terminal. Found a false positive? Report it.