...
However, when a thread is updating the value of itemsInInventory
, it is possible for other threads to read the original value (that is, the value before the update). Furthermore, it is possible for two threads to perform the --
operator simultaneously. If this happens, both will read the same value, decrement it, and write the decremented value. This causes itemsInInventory
to be decremented by 1 even though it was decremented twice! This is because the post decrement operator is nonatomic.
...
This guarantees that once the update has taken place, it is immediately visible to all threads that read the field. However, when a thread is in the process of updating the value of itemsInInventory
(after the read and modification, but before the write), it is still possible for other threads to read the original value (that is, the value before the update). Furthermore, two threads may still decrement itemsInInventory
at the same time, resulting in an incorrect value. This is because the post decrement operator is nonatomic even when volatile
is used.
...
Code Block | ||
---|---|---|
| ||
private final AtomicInteger itemsInInventory = new AtomicInteger(100);
private final int removeItem() {
for (;;) {
int old = itemsInInventory.get();
if (old > 0) {
int next = old - 1; // Decrement
if (itemsInInventory.compareAndSet(old, next)) {
return next; // Returns new count of items in inventory
}
} else {
return -1; // Error code
}
}
}
|
Wiki Markup |
---|
According to the Java API \[[API 06|AA. Java References#API 06]\], class {{AtomicInteger}} documentation: |
...