52 lines
1.1 KiB
Plaintext
52 lines
1.1 KiB
Plaintext
``++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) {
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== See
|
|
|
|
* 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)
|
|
|
|
include::message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|