
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
62 lines
1.3 KiB
Plaintext
62 lines
1.3 KiB
Plaintext
== 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[]
|