...
However, this code is not thread-safe. Multiple threads may not observe the latest state of the flag
because ^=
constitutes a non-atomic operation.
Noncompliant Code Example (volatile
variable)
This noncompliant code example derives from the preceding one but declares the flag
as volatile
.
Code Block | ||
---|---|---|
| ||
class Foo {
private volatile boolean flag = true;
public void toggle() { // unsafe
flag ^= true;
}
public boolean getFlag() { // safe
return flag;
}
}
|
It is still insecure for multithreaded use because volatile
does not guarantee the visibility of updates to the shared variable flag
when a compound operation is performed.
Compliant Solution (synchronization)
This compliant solution synchronized the toggle()
method to ensure that the flag
is made visible to all the threads.
For example, consider two threads that call toggle()
. Theoretically the effect of toggling flag
twice should restore it to its original value. But the following scenario could occur, leaving flag
in the wrong state.
Time | flags= | Thread | Action |
---|---|---|---|
1 | true | t1 | reads the current value of |
2 | true | t2 | reads the current value of |
3 | true | t1 | toggles the temporary variable to false |
4 | true | t2 | toggles the temporary variable to false |
5 | false | t1 | writes the temporary variable value to |
6 | false | t2 | writes the temporary variable value to |
As a result, the effect of the call by t1 is not reflected in flag
; the program behaves as if the call was never made.
Noncompliant Code Example (volatile
variable)
This noncompliant code example derives from the preceding one but declares the flag
as volatile
.
Code Block | ||
---|---|---|
| ||
class Foo {
private volatile boolean flag = true;
public void toggle() { // unsafe
flag ^= true | ||
Code Block | ||
| ||
class Foo { private volatile boolean flag = true; public synchronized void toggle() { flag ^= true; // same as flag = !flag; } public boolean getFlag() { // safe return flag; } } |
Compliant Solution (java.util.concurrent.atomic.AtomicBoolean
)
This compliant solution uses the java.util.concurrent.atomic.AtomicBoolean
type to declare the flag
.
Code Block | ||
---|---|---|
| ||
class Foo {
private AtomicBoolean flag = new AtomicBoolean(true);
public void toggle() {
boolean temp;
do {
temp = flag.get();
} while(!flag.compareAndSet(temp, !temp));
}
public AtomicBoolean getFlag() {
return flag;
}
}
|
It ensures that updates to the variable are carried out by using the compareAndSet()
method of the class AtomicBoolean
. All updates are made visible to other threads.
Noncompliant Code Example (increment/decrement)
Prefix and postfix, increment and decrement operations are non-atomic in that the value written depends upon the value initially read from the operand. For example, x++
is non-atomic because it is a composite operation consisting of three discrete operations: reading the current value of x
, adding one to it, and writing the new, incremented value back to x
.
This noncompliant code example contains a data race that may result in the itemsInInventory
field failing to account for removed items.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private static final int MIN_INVENTORY = 3;
private int itemsInInventory = 100;
public final void removeItem() {
if (itemsInInventory <= MIN_INVENTORY) {
throw new IllegalStateException("Under stocked");
}
itemsInInventory--;
}
}
|
For example, if the removeItem()
method is concurrently invoked by two threads, t1 and t2, the execution of these threads may be interleaved so that:
Time | itemsInInventory= | Thread | Action |
---|---|---|---|
1 | 100 | t1 | reads the current value of |
2 | 100 | t2 | reads the current value of |
3 | 100 | t1 | decrements the temporary variable to 99 |
4 | 100 | t2 | decrements the temporary variable to 99 |
5 | 99 | t1 | writes the temporary variable value to |
6 | 99 | t2 | writes the temporary variable value to |
As a result, the effect of the call by t1 is not reflected in itemsInInventory
; the program behaves as if the call was never made.
As another example, suppose itemsInInventory currently has the value MIN_INVENTORY + 1. If the removeItem()
method is concurrently invoked by two threads, t1 and t2, the execution of these threads may be interleaved so that:
Time | itemsInInventory= | Thread | Action |
---|---|---|---|
1 | MIN_INVENTORY+1 | t1 | checks that the current value of |
2 | MIN_INVENTORY+1 | t2 | checks that the current value of |
3 | MIN_INVENTORY+1 | t1 | reads the current value of |
4 | MIN_INVENTORY | t1 | decrements the temporary variable to MIN_INVENTORY |
5 | MIN_INVENTORY | t1 | writes the temporary variable value to |
6 | MIN_INVENTORY | t2 | reads the current value of |
7 | MIN_INVENTORY-1 | t2 | decrements the temporary variable to MIN_INVENTORY-1 |
8 | MIN_INVENTORY-1 | t2 | writes the temporary variable value to |
As a result, both threads decrement itemsInInventory
but the range check on the variable is bypassed, causing the variable to have an invalid value. The decrement operation may even wrap if MIN_INVENTORY == Integer.MIN_VALUE
.
Noncompliant Code Example (volatile)
This noncompliant code example attempts to resolve the problem by declaring itemsInInventory
volatile.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private static final int MIN_INVENTORY = 3;
private volatile int itemsInInventory = 100;
public final void removeItem() {
if (itemsInInventory <= MIN_INVENTORY) {
throw new IllegalStateException("under stocked");
}
itemsInInventory--;
}
}
|
Volatile variables are unsuitable when more than one read/write operation needs to be atomic. The use of a volatile variable in this noncompliant code example guarantees that once itemsInInventory
has been updated, the new value is visible to all threads that read the field. However, because the post decrement operator is nonatomic, even when volatile
is used, the interleaving described in the previous noncompliant code example is still possible. Furthermore, the race codnition imposed by range-checking itemsInInventory
before decrementing it is also still possible.
Compliant Solution (java.util.concurrent.atomic
classes)
The java.util.concurrent
utilities can be used to atomically manipulate a shared variable. This compliant solution defines intemsInInventory
as a java.util.concurrent.atomic.AtomicInteger
variable, allowing composite operations to be performed atomically.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private static final int MIN_INVENTORY = 3;
private final AtomicInteger itemsInInventory = new AtomicInteger(100);
public final void removeItem() {
while (true) {
int old = itemsInInventory.get();
if (old <= MIN_INVENTORY) {
throw new IllegalStateException("Under stocked");
}
int next = old - 1; // Decrement
if (itemsInInventory.compareAndSet(old, next)) {
break;
}
} // end while
} // end removeItem()
}
|
Note that updates to shared atomic variables are visible to other threads.
Wiki Markup |
---|
The {{compareAndSet()}} method takes two arguments, the expected value of a variable when the method is invoked and the updated value. This compliant solution uses this method to atomically set the value of {{itemsInInventory}} to the updated value if and only if the current value equals the expected value \[[API 06|AA. Java References#API 06]\]. The {{while}} loop ensures that the {{removeItem()}} method succeeds in decrementing the most recent value of {{itemsInInventory}} as long as the inventory count is greater than {{MIN_INVENTORY}}. |
Compliant Solution (method synchronization)
Synchronization provides a way to safely share object state across multiple threads without the need to reason about reorderings, compiler optimizations, and hardware specific behavior.
This compliant solution uses method synchronization to synchronize access to itemsInInventory
. Consequently, access to itemsInInventory
is mutually exclusive and its state consistent across all threads.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private static final int MIN_INVENTORY = 3;
private int itemsInInventory = 100;
public final synchronized void removeItem() {
if (itemsInInventory <= MIN_INVENTORY) {
throw new IllegalStateException("Under stocked");
}
itemsInInventory--;
}
}
|
If code is synchronized correctly, updates to shared variables are instantly made visible to other threads. Synchronization is more expensive than using the optimized java.util.concurrent
utilities and should generally be preferred when it is sufficiently complex to carry out the operation atomically using the utilities. When using synchronization, care must be taken to avoid deadlocks (see CON12-J. Avoid deadlock by requesting and releasing locks in the same order).
Compliant Solution (block synchronization)
Constructors and methods can use block synchronization as an alternative to method synchronization. Block synchronization synchronizes a block of code rather than a method, as shown in this compliant solution.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private static final int MIN_INVENTORY = 3;
private int itemsInInventory = 100;
private final Object lock = new Object();
public final void removeItem() {
synchronized(lock) {
if (itemsInInventory <= MIN_INVENTORY) {
throw new IllegalStateException("Under stocked");
}
itemsInInventory--;
}
}
}
|
Block synchronization is preferable over method synchronization because it enables reduction of the duration for which the lock is held. This is because statements that do not require synchronization can be safely moved out of the synchronized block. This compliant solution requires all statements to be synchronized and consequently, is comparable to the previous compliant solution with respect to performance.
Block synchronization when used in conjunction with a private
internal lock object also protects against denial of service attacks. Block synchronization does not require synchronizing on an internal private lock object instead of the intrinsic lock of the class's object (this
reference). However, it is more secure to synchronize on an internal private lock object instead of a more accessible lock object. See CON04-J. Use the private lock object idiom instead of the Class object's intrinsic locking mechanism for more information.
Compliant Solution (ReentrantLock
)
This compliant solution uses a java.util.concurrent.locks.ReentrantLock
to atomically perform the post-decrement operation.
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private static final int MIN_INVENTORY = 3;
private int itemsInInventory = 100;
private final Lock lock = new ReentrantLock();
public final void removeItem() {
if (lock.tryLock()) {
try {
if (itemsInInventory <= MIN_INVENTORY) {
throw new IllegalStateException("Under stocked");
}
itemsInInventory--;
} finally {
lock.unlock();
}
}
} // end removeItem()
}
|
Code that uses this lock behaves similar to synchronized code that uses the traditional monitor lock. ReentrantLock
provides several other capabilities, for instance, the tryLock()
method does not block waiting if another thread is already holding the lock. The class java.util.concurrent.locks.ReentrantReadWriteLock
can be used when some thread requires a lock to write information while other threads require the lock to concurrently read the information.
...
|
It is still insecure for multithreaded use because volatile
does not guarantee the visibility of updates to the shared variable flag
when a compound operation is performed.
Compliant Solution (synchronization)
This compliant solution synchronized the toggle()
method to ensure that the flag
is made visible to all the threads.
Code Block | ||
---|---|---|
| ||
class Foo {
private volatile boolean flag = true;
public synchronized void toggle() {
flag ^= true; // same as flag = !flag;
}
public boolean getFlag() {
return flag;
}
}
|
Compliant Solution (java.util.concurrent.atomic.AtomicBoolean
)
This compliant solution uses the java.util.concurrent.atomic.AtomicBoolean
type to declare the flag
.
Code Block | ||
---|---|---|
| ||
class Foo {
private AtomicBoolean flag = new AtomicBoolean(true);
public void toggle() {
boolean temp;
do {
temp = flag.get();
} while(!flag.compareAndSet(temp, !temp));
}
public AtomicBoolean getFlag() {
return flag;
}
}
|
It ensures that updates to the variable are carried out by using the compareAndSet()
method of the class AtomicBoolean
. All updates are made visible to other threads.
Noncompliant Code Example (addition)
In this noncompliant code example, the two fields a
and b
may be set by multiple threads, using the setValues()
method.
Code Block | ||
---|---|---|
| ||
private volatile int a; private volatile int b; public int getSum() throws ArithmeticException { // Check for integer overflow if( b > 0 ? a > Integer.MAX_VALUE - b : a < Integer.MIN_VALUE - b ) { throw new ArithmeticException("Not in range"); } class Adder { private int a; private int b; public int getSum() { return a + b; } public void setValues(int a, int b) { this.a = a; this.b = b; } } |
The getSum()
method may return a different sum every time it is invoked from different threads. For instance, if a
and b
currently have the value 0, and one thread calls getSum()
while another calls setValues(1, 1)
, then getSum()
might return 0, 1, or 2. Of these, the value 1 is unacceptable; it is returned when the first thread reads a
and b
, after the second thread has set the value of a
but before it has set the value of b
.
This code also does nothing to prevent arithmetic overflow. See INT00-J. Perform explicit range checking to ensure integer operations do not overflow for more information.
Noncompliant Code Example (
...
overflow check, atomic integer fields)
The issues described in the previous noncompliant code example can also arise even when the volatile variables a
and b
are replaced with atomic integers.
Code Block | ||
---|---|---|
| ||
class Adder { private final AtomicInteger a = new AtomicInteger(); private final AtomicInteger b = new AtomicInteger(); public int getSum() throws ArithmeticException { // Check for integer overflow if( b.get() > 0 ? a.get() > Integer.MAX_VALUE - b.get() : a.get() < Integer.MIN_VALUE - b.get() ) { throw new ArithmeticException("Not in range"); } return a.get() + b.get(); // or, return a.getAndAdd(b.get()); } public void setValues(int a, int b) { this.a.set(a); this.b.set(b); } , return a.getAndAdd(b.get()); } public void setValues(int a, int b) { this.a.set(a); this.b.set(b); } } |
For example, when a thread is executing setValues()
another may invoke getSum()
and retrieve an incorrect result. Furthermore, in the absence of synchronization, there are data races in the check for integer overflow. For instance, a thread can call setValues()
after a second thread has read a
, but before it has read b
in order to add them together; in which case, the second thread will get an improper addition. Even worse, a thread can call setValues()
after a second thread has verified that overflow will not occur, but before the second thread reads the values to add. This would cause the second thread to add two values that have not been checked for overflow, and overflow when adding themFor example, when a thread is executing setValues()
another may invoke getSum()
and retrieve an incorrect result. Furthermore, in the absence of synchronization, there are data races in the check for integer overflow.
Compliant Solution (addition, synchronized)
This compliant solution synchronizes the setValues()
method and getSum()
methods so that the entire operation is atomic.
Code Block | ||
---|---|---|
| ||
class Adder { private int a; private int b; public synchronized int getSum() throws ArithmeticException { // Check for integer overflow if( b > 0 ? a > Integer.MAX_VALUE - b : a < Integer.MIN_VALUE - b ) { throw new ArithmeticException("Not in range"); } return a + b; } public synchronized void setValues(int a, int b) { this.a = a; this.b = b; } } |
Unlike the noncompliant code example, if a
and b
currently have the value 0, and one thread calls getSum()
while another calls setValues(1, 1)
, getSum()
may return return 0, or 2, depending on which thread obtains the intrinsic lock first. The locking guarantees that getSum()
will never return the unacceptable value 1.
...