rspec/rules/S3064/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

89 lines
2.2 KiB
Plaintext

== Why is this an issue?
Double-checked locking can be used for lazy initialization of ``++volatile++`` fields, but only if field assignment is the last step in the ``++synchronized++`` block. Otherwise you run the risk of threads accessing a half-initialized object.
=== Noncompliant code example
[source,java]
----
public class MyClass {
private volatile List<String> strings;
public List<String> getStrings() {
if (strings == null) { // check#1
synchronized(MyClass.class) {
if (strings == null) {
strings = new ArrayList<>(); // Noncompliant
strings.add("Hello"); //When threadA gets here, threadB can skip the synchronized block because check#1 is false
strings.add("World");
}
}
}
return strings;
}
}
----
=== Compliant solution
[source,java]
----
public class MyClass {
private volatile List<String> strings;
public List<String> getStrings() {
if (strings == null) { // check#1
synchronized(MyClass.class) {
if (strings == null) {
List<String> tmpList = new ArrayList<>();
tmpList.add("Hello");
tmpList.add("World");
strings = tmpList;
}
}
}
return strings;
}
}
----
== Resources
* https://wiki.sei.cmu.edu/confluence/x/6zdGBQ[CERT, LCK10-J.] - Use a correct form of the double-checked locking idiom
=== Related rules
* S2168 - Double-checked locking should not be used
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Fully initialize this new "xxx" before assigning it to the field.
'''
== Comments And Links
(visible only on this page)
=== on 15 Jun 2015, 18:07:41 Ann Campbell wrote:
\[~tamas.vajk] I've targeted this to C# because I think it might be relevant.
=== on 17 Aug 2015, 06:56:13 Tamas Vajk wrote:
\[~ann.campbell.2] This seems very specific (to Java), I wouldn't target C#. There might be minor differences in the Java and C# memory model when using ``++volatile++``, which I'm not aware of.
=== on 17 Aug 2015, 16:08:28 Ann Campbell wrote:
Thanks for the review [~tamas.vajk]. Un-targeted.
endif::env-github,rspecator-view[]