...
Synchronizing the code makes it easier to reason about its behavior and is frequently more secure than simply using the volatile
keyword. However, synchronization has a somewhat higher performance overhead and can result in thread contention and deadlocks when used excessively.
Declaring a variable volatile or correctly synchronizing the code guarantees that 64-bit primitive long
and double
variables are accessed atomically. (For more information on sharing those variables among multiple threads, see guideline VNA05-J. Ensure atomicity when reading and writing 64-bit values.)
...
This noncompliant code example uses a shutdown()
method to set a non-volatile done
flag that is checked in the run()
method.
Code Block | ||
---|---|---|
| ||
final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } } } public void shutdown() { done = true; } } |
...
In this compliant solution, the done
flag is declared as volatile to ensure that writes are visible to other threads.
Code Block | ||
---|---|---|
| ||
final class ControlledStop implements Runnable { private volatile boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { // Handle exception Thread.currentThread().interrupt(); // Reset interrupted status } } } public void shutdown() { done = true; } } |
If one thread invokes the shutdown() method to set the flag, a second thread might not observe that change. Consequently, the second thread may observe that done is still false and incorrectly invoke the sleep() method. A compiler is allowed to optimize the code if it determines that the value of done is never modified by the same thread, resulting in an infinite loop.
Compliant Solution (java.util.concurrent.atomic.AtomicBoolean
)
In this compliant solution, the done
flag is declared as AtomicBoolean
. Atomic types also guarantee that writes are visible to other threads.
...
Code Block | ||
---|---|---|
| ||
final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!isDone()) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { // Handle exception Thread.currentThread().interrupt(); // Reset interrupted status } } } public synchronized boolean isDone() { return done; } public synchronized void shutdown() { done = true; } } |
...
Synchronization is a more secure alternative in situations where the volatile
keyword or a java.util.concurrent.atomic.Atomic*
field is inappropriate, such as if a variable's new value depends on its current value. For more information, see guideline VNA02-J. Ensure that compound operations on shared variables are atomic.
Compliance with guideline LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code can reduce the likelihood of misuse by ensuring that untrusted callers cannot access the lock object.
Exceptions
CON00VNA00-EX1: Class
objects need not be made visible because they are created by the virtual machine and their initialization always precedes any subsequent use.
...
Failing to ensure the visibility of a shared primitive variable may result in a thread observing a stale value of the variable.
Rule Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON00 VNA00- J | medium | probable | medium | P8 | L2 |
...
References
Wiki Markup |
---|
\[[JLS 052005|AA. Java References#JLS 05]\] [Chapter 17, Threads and Locks|http://java.sun.com/docs/books/jls/third_edition/html/memory.html], Section 17.4.5 Happens-Before Order, Section 17.4.3 Programs and Program Order, Section 17.4.8 Executions and Causality Requirements \[[Bloch 082008|AA. Java References#Bloch 08]\] Item 66: Synchronize access to shared mutable data \[[Goetz 062006|AA. Java References#Goetz 06]\] 3.4.2. "Example: Using Volatile to Publish Immutable Objects" \[[JPL 062006|AA. Java References#JPL 06]\] 14.10.3. "The Happens-Before Relationship" \[[MITRE 092009|AA. Java References#MITRE 09]\] [CWE ID 667|http://cwe.mitre.org/data/definitions/667.html] "Insufficient Locking," [CWE ID 413|http://cwe.mitre.org/data/definitions/413.html] "Insufficient Resource Locking," [CWE ID 567|http://cwe.mitre.org/data/definitions/567.html] "Unsynchronized Access to Shared Data" |
...