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

73 lines
2.0 KiB
Plaintext

== Why is this an issue?
Using compound operators as well as increments and decrements (and toggling, in the case of ``++boolean++``s) on primitive fields are not atomic operations. That is, they don't happen in a single step. For instance, when a ``++volatile++`` primitive field is incremented or decremented you run the risk of data loss if threads interleave in the steps of the update. Instead, use a guaranteed-atomic class such as ``++AtomicInteger++``, or synchronize the access.
=== Noncompliant code example
[source,java]
----
private volatile int count = 0;
private volatile boolean boo = false;
public void incrementCount() {
count++; // Noncompliant
}
public void toggleBoo(){
boo = !boo; // Noncompliant
}
----
=== Compliant solution
[source,java]
----
private AtomicInteger count = 0;
private boolean boo = false;
public void incrementCount() {
count.incrementAndGet();
}
public synchronized void toggleBoo() {
boo = !boo;
}
----
== Resources
* https://wiki.sei.cmu.edu/confluence/x/SjdGBQ[CERT, VNA02-J.] - Ensure that compound operations on shared variables are atomic
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use an "Atomic[Integer|Long]" for this field; its operations are atomic.
'''
== Comments And Links
(visible only on this page)
=== on 18 Jun 2015, 18:34:53 Nicolas Peru wrote:
Title was a bit ambiguous I let you modify it if you think it is a bit redundant.
=== on 18 Jun 2015, 18:36:55 Ann Campbell wrote:
Thank you [~nicolas.peru]. That's what I get for writing the title before I fully understand what the description should say. :)
=== on 19 Jun 2015, 15:50:31 Ann Campbell wrote:
\[~nicolas.peru] I just realized that in response to your 'redundant' comment I simply undid the change you had made. But at root, is there a 'safe' way to increment a ``++volatile++`` var?
=== on 13 Oct 2015, 08:06:59 Nicolas Peru wrote:
Modified title.
endif::env-github,rspecator-view[]