63 lines
1.3 KiB
Plaintext
63 lines
1.3 KiB
Plaintext
Primitives can be read and written to atomically. Except for ``++long++`` and ``++double++``, that is. These 64-bit primitives must be marked ``++volatile++`` in multi-threaded environments, or swapped out for their atomic counterparts: ``++AtomicLong++``, and ``++AtomicDouble++`` to guarantee that their updates are always visible to other threads.
|
|
|
|
|
|
Similarly, to ensure that updates to 32-bit primitives are visible to all threads, they should also be marked ``++volatile++``.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,java]
|
|
----
|
|
long m = 0; // Noncompliant
|
|
|
|
public void increment() {
|
|
m++;
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
[source,java]
|
|
----
|
|
volatile long m = 0;
|
|
|
|
public void increment() {
|
|
m++;
|
|
}
|
|
----
|
|
or
|
|
|
|
[source,java]
|
|
----
|
|
AtomicLong m = new AtomicLong(0);
|
|
|
|
public void increment() {
|
|
m.incrementAndGet();
|
|
}
|
|
----
|
|
|
|
|
|
== See
|
|
|
|
* https://wiki.sei.cmu.edu/confluence/x/QTdGBQ[CERT, VNA00-J.] - Ensure visibility when accessing shared primitive variables
|
|
* https://wiki.sei.cmu.edu/confluence/x/zzdGBQ[CERT, VNA05-J.] - Ensure atomicity when reading and writing 64-bit values
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
include::highlighting.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|