getClass
should not be used for synchronization in non-final
classes because child classes will synchronize on a
different object than the parent or each other, allowing multiple threads into the code block at once, despite the synchronized
keyword.
Instead, hard code the name of the class on which to synchronize or make the class final
.
Noncompliant code example
public class MyClass {
public void doSomethingSynchronized(){
synchronized (this.getClass()) { // Noncompliant
// ...
}
}
Compliant solution
public class MyClass {
public void doSomethingSynchronized(){
synchronized (MyClass.class) {
// ...
}
}