Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor grammar fixes; normative text checked.

...

Declaring a shared variable volatile guarantees visibility in a thread-safe manner only when both of the following conditions are met:

Wiki Markup
The first condition can be relaxed when you can be sure that only one thread will ever update the value of the variable \[[Goetz 2006|AA. Bibliography#Goetz 06]\]. However, code that relies on a single-thread confinement is error-prone and difficult to maintain. This design behaviorapproach is permissiblepermitted under this guideline, but notis recommendeddiscouraged.

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 both guarantee that 64-bit primitive long and double variables are will be 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.)

...

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 Compilers and JITs are allowed to optimize the code if it determines when they determine that the value of done is never modified by the same thread, resulting in an infinite loop.

...

Exceptions

VNA00-EX1: Class objects need not be made visible because they are created by the virtual machine and ; their initialization always precedes any subsequent use. Consequently, cross-thread visibility of Class objects is already assured by default

Risk Assessment

Failing to ensure the visibility of a shared primitive variable may result in a thread observing a stale value of the variable.

...

MITRE CWE: CWE-567 "Unsynchronized Access to Shared Data"

Bibliography

Wiki Markup
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 66: Synchronize access to shared mutable data
\[[Goetz 2006|AA. Bibliography#Goetz 06]\] 3.4.2. "Example: Using Volatile to Publish Immutable Objects"
\[[JLS 2005|AA. Bibliography#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 2008|AA. Bibliography#Bloch 08]\] Item 66: Synchronize access to shared mutable data
\[[Goetz 2006|AA. Bibliography#Goetz 06]\] 3.4.2. "Example: Using Volatile to Publish Immutable Objects"
\[[JPL 2006|AA. Bibliography#JPL 06]\] 14.10.3. "The Happens-Before Relationship"

...