Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
private volatile int itemsInInventory = 100;

public int removeItem() {
  if(itemsInInventory > 0synchronized(this) {
    synchronized(thisif(itemsInInventory > 0) {
      return itemsInInventory--;  // Returns new count of items in inventory
    }
    } else {
      return 0;
    }
  }
}

Block synchronization is more preferable than method synchronization because it reduces the period for which the lock is held and also protects against denial of service attacks. The variable itemsInInventory still needs to be declared volatile because the check to determine whether it is greater than 0 relies on the latest value of the variable. An alternative to avoid the need to declare the variable volatile is to use block synchronization across the whole if-else block. However, this alternative is more costly.

...