Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor

...

Code Block
bgColor#FFcccc
private int itemsInInventory = 100;

public final int removeItem() {
  if (itemsInInventory > 0) {
    return itemsInInventory--;  // Returns new count of items in inventory
  } 
  return -1; // Error code  
}

For example, if the remoteItemremoveItem() method is concurrently invoked by two threads, the execution of these threads may be interleaved so that:

...

This noncompliant code example attempts to repair resolve the problem by declaring the itemsInInventory as volatile.

...

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 immediately visible to all threads that read the field. However, because the post decrement operator is non-atomicnonatomic, even when {{volatile is used, the interleaving described in the previous noncompliant code exampleis example is still possible.

Compliant Solution (java.util.concurrent.atomic classes)

...

Block synchronization is preferable over method synchronization because it reduces the duration for which the lock is held and also protects against denial of service attacks. Block synchronization requires synchronizing on a an internal private lock object instead of the intrinsic lock of the class's object (see CON04-J. Use the private lock object idiom instead of the Class object's intrinsic locking mechanism).

...