rspec/rules/S3067/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
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.
2023-05-25 14:18:12 +02:00

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[]