Wiki Markup |
---|
Composite operations on shared variables (consisting of more than one discrete operation) must be performed atomically. Errors can arise from composite operations that need to be perceived atomically but are not \[[JLS 05|AA. Java References#JLS 05]\]. For example, any assignment that depends on an existing value is a composite operation, forsuch example,as: {{a = b}}. The Incrementincrement {{+\+}} and decrement {{-\-}} operators depend modify the value of the operand based on the existing value of the operand and are consequently always composite operations. Compound assignmentsassignment expressions that include a compound assignment operators {{*=, /=, %=, +=, -=, <<=, >>=, >>>=, ^=, or |=}} are always composite operations. A compound assignment expression of the form _E1 op= E2_ is equivalent to _E1 = (T )((E1) op (E2))_, where _T_ is the type of _E1_, except that _E1_ is evaluated only once. |
...
Noncompliant Code Example (increment/decrement)
Pre- and post-increment operations and pre- and post-decrement operations in Java 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
.
...
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.
Noncompliant Code Example (volatile)
This noncompliant code example attempts to resolve the problem by declaring itemsInInventory
volatile.
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 | ||
---|---|---|
| ||
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 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)
...
Code Block | ||
---|---|---|
| ||
class InventoryManager { private static final int MIN_INVENTORY = 3; private final AtomicInteger itemsInInventory = new AtomicInteger(100); public final void removeItem() { forwhile (;;true) { int old = itemsInInventory.get(); if (old ><= MIN_INVENTORY) { intthrow next = old - 1; // Decrementnew IllegalStateException("Under stocked"); if(itemsInInventory.compareAndSet(old, next)) {} int next = break; } old - 1; // Decrement } elseif (itemsInInventory.compareAndSet(old, next)) { throw new IllegalStateException("Under stocked")break; } } // end forwhile } // 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 {{forwhile}} 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}}. |
...
Code Block | ||
---|---|---|
| ||
class InventoryManager {
private static final int MIN_INVENTORY = 3;
private int itemsInInventory = 100;
private final Object lock = new Object();
public final synchronized void removeItem() {
synchronized(lock) {
if (itemsInInventory <= MIN_INVENTORY) {
throw new IllegalStateException("Under stocked");
}
itemsInInventory--;
}
}
}
|
Block synchronization is preferable over method synchronization because it reduces enables reduction of the duration for which the lock is held and 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. 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).
...
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 similarly 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.
...
Code Block | ||
---|---|---|
| ||
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); } |
...