== Why is this an issue?

``++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

[source,java]
----
public class MyClass {
  public void doSomethingSynchronized(){
    synchronized (this.getClass()) {  // Noncompliant
      // ...
    }
  }
----


=== Compliant solution

[source,java]
----
public class MyClass {
  public void doSomethingSynchronized(){
    synchronized (MyClass.class) {
      // ...
    }
  }
----


== Resources

* https://wiki.sei.cmu.edu/confluence/x/qTdGBQ[CERT, LCK02-J.] - Do not synchronize on the class object returned by getClass()


ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Synchronize on the static class name instead.


'''
== Comments And Links
(visible only on this page)

=== on 15 Jun 2015, 20:15:20 Nicolas Peru wrote:
Looks good.

=== on 17 Aug 2018, 16:28:58 Amaury Levé wrote:
https://jira.sonarsource.com/browse/RSPEC-2551[RSPEC-2551] implements the same behavior for C#.

endif::env-github,rspecator-view[]
