Wiki Markup |
---|
Memory that can be shared between threads is called _shared memory_ or _heap memory_. The term _variable_ is used in the context of this guideline, to refer to both fields and array elements \[[JLS 05|AA. Java References#JLS 05]\]. |
static
fields, and array elements are stored in heap memory. Local variables, formal method parameters, or exception handler parameters are never shared between threads and are not affected by the memory modelVariables that are shared between threads are referred to as shared variables. All instance fields, {{static}} fields, and array elements are shared variables and are stored in heap memory. Local variables, formal method parameters, or exception handler parameters are never shared between threads and are not affected by the [memory model|BB. Definitions#memory model]. |
The Java Language Specification defines the Java Memory Model (JMM) which describes possible behaviors of a multi-threaded Java program. Concurrent executions are typically interleaved but the situation is complicated by statements that may be reordered by the compiler or runtime system. This results in execution orders that are not immediately obvious from an examination of the source-codeIf the correctness of the constituting code is based on its execution characteristics in a single threaded environment, the code may be unsafe for use in a multi-threaded environment. Two kinds of hazards, visibiity and reordering, occur when special concurrency primitives are not used in such code.
Visibility refers to the requirement that every thread sees the value of the most recent update to a shared variable. This is essential in multi-threaded programs because the value of a shared variable may be cached and not written to main memory immediately. Consequently, another thread may retrieve a stale value of the variable when attempting to read it from the main memory. Using the volatile
keyword mitigates this risk and so does correct synchronization.
The restricted or no reordering requirement refers to ensuring that the execution sequence of a set of statements does not vary when observed by multiple threads. Concurrent executions of code are typically interleaved and statements may be reordered by the compiler or runtime system to facilitate various optimizations. This results in execution orders that are not immediately obvious from an examination of the source-code. Failure to account for this hazard is a common source of data races. Restricting the set of possible reorderings makes it easier to reason about the safety of the code. This risk is mitigated by correctly synchronizing the code and in some cases, by using the volatile
keyword.
Even if statements execute in the expected order (program order), caching can prevent the latest values from being reflected in the main memory (visibility hazard). Program order is the execution order that is expected when a single thread is running the statements sequentially, as written in a method.
There are two requirements for implementing synchronization correctlywriting provably correct multi-threaded code:
1. Happens-before consistency: If two accesses of a shared variable follow the happens-before relationship, data races arising from statement reorderings cannot occur. However, this is necessary but not sufficient for acceptable program behavior. In addition, often the particular execution order of a program must be sequential consistent.
Consider the following example in which a
and b
are (shared) global variables or instance fields but r1
and r2
are local variables not accessible by other threads.
...
Because, in Thread 1
, the two assignments a = 10;
and r1 = b;
are not related, the compiler or runtime system is free to reorder them. Similarly in Thread 2
, the statements may be freely reordered. Although it may seem counter-intuitive, the Java memory model allows a read to see a write that occurs later in the execution order.
Two A possible execution orders and order showing actual assignments areis:
Execution Order | Assignment | Assigned Value | Notes |
---|---|---|---|
1. |
| 10 |
|
2. |
| 20 |
|
3. |
| 0 | Reads initial value of |
4. |
| 0 | Reads initial value of |
In this ordering, r1
and r2
read the original values of the variables a
and b
even though they are expected to see the updated values, 10 and 20. Another possible execution order showing actual assignments is:
Execution Order | Statement | Assigned Value | Notes |
---|---|---|---|
1. |
| 20 | Reads later value (in step 4.) of write, that is 20 |
2. |
| 10 | Reads later value (in step 3.) of write, that is 10 |
3. |
| 10 |
|
4. |
| 20 |
|
In this ordering, r1
and r2
read the values of a
and b
written from step 3 and 4, even before the statements corresponding to these steps are have executed.
Wiki Markup |
---|
"The fact that we allow a read to see a write that comes later in the execution order can sometimes thus result in unacceptable behaviors." \[[JLS 05|AA. Java References#JLS 05]\]. |
Both, the use of synchronization and the {{volatile}} keyword prevent a thread from observing inconsistent values of shared variables. |
2. Sequential consistency: This property provides a very strong guarantee that the compiler will not optimize away or reorder any statements. It guarantees that the program is free from data races. It also ensures that each access of a variable is atomic and immediately visible to other threads.
For example, consider some a set of statements that are being executed by multiple threads:
...
In the previous example, Statement 3 writes to a volatile
variable, and statement 4 in the second thread, reads the same volatile
variable. The read sees the most recent write (to the same variable v
) from statement 3. This may not be true in the happens-before order because a future read can always see the default or previous value of v
instead of the one set in the most recent write. This guarantee is provided by the sequential consistency property of volatile
accesses.
...
Volatile read and write operations cannot be reordered with respect to each other and in addition, as required by the JMM, volatile
read and write operations are also not reordered with respect to operations on non-volatile nonvolatile variables. When reading the volatile
variable, the other thread will also see statements occurring before the write to the volatile
variable , to have already executed, with prior occurrences of volatile
and non-volatile nonvolatile fields assuming the assigned values.
...
Code Block | ||
---|---|---|
| ||
final class ControlledStop implements Runnable { private volatile boolean done = false; // ... } |
Noncompliant Code Example (nonvolatile guard)
This noncompliant code example declares a non-volatile int
variable that is initialized in the constructor depending on a security check. In a multi-threading scenario, it is possible that the statements will be reordered so that the boolean
flag initialized
is set to true
before the initialization has concluded. If it is possible to obtain a partially initialized instance of the class in a subclass using a finalizer attack (OBJ04-J. Do not allow partially initialized objects to be accessed), a race condition can be exploited by invoking the getBalance()
method to obtain the balance even though initialization is still underway.
...