A synchronized block locks getClass(), which differs between subclasses

tx0/java:lock-on-get-classrecommendedwarningbug, concurrency

What it finds

synchronized (getClass()) locks a different object in each subclass: an instance of a subclass locks the subclass's Class, so code in the class and in its subclasses does not exclude each other. Naming the class, synchronized (Account.class), locks the same object for all of them.

From the rule's source, lock_on_get_class.rs.

Example from the rule's tests
class Counter {  static int total;   void add() {    synchronized (getClass()) {tx0 reports: getClass() is a different lock in each subclass      total++;    }    synchronized (this.getClass()) {tx0 reports: getClass() is a different lock      total++;    }    synchronized (Counter.class) {      total++;    }  }}
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 from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:lock-on-get-class" = "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:lock-on-get-class] reason="..."

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