Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: tightened the atomicinteger CS

...

Code Block
bgColor#ccccff
class InventoryManager {
  private final AtomicInteger itemsInInventory = new AtomicInteger(100);

  public final void returnItem() {
    while (true)int old;
    do {
      intold old = itemsInInventory.get();
      if (old == Integer.MAX_VALUE) {
        throw new IllegalStateException("Out of bounds");
      }
      int next = old + 1; // Decrement
      if (} while (!itemsInInventory.compareAndSet(old, nextitemsInInventory.incrementAndGet())) {
        break;
      }
    } // end while
  } // end removeItem()
} 

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}}. Refer to [CON01-J. Ensure that compound operations on shared variables are atomic] for more details.

...