Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: starting to wonder if we shouldn't reverse the condition on the test against MIN_INVENTORY

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]\].

...

This noncompliant code example contains a data race that may result in the itemsInInventory field missing the fact that callers returned or failing to account for removed items.

Code Block
bgColor#FFcccc
public class InventoryManagementInventoryManager {

  private static final int MIN_INVENTORY = 103;
  private static final int MAX_INVENTORY = 500;

  private int itemsInInventory = 100;

  public final void removeItem() {
    if (itemsInInventory <= MIN_INVENTORY()) {
      throw new IllegalStateException("under stocked");
    }
    itemsInInventory--;
  }

  public final void returnItem() {
    if (itemsInInventory == MAX_INVENTORY) {
      throw new IllegalStateException("over stocked");
    }
    itemsInInventory++;
  }

} 
} 

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

...

As a result, the effect of the call by t1 is not reflected in itemsInInventory. It is ; the program behaves as if the call was never made. This "lost call" phenomenon can occur with concurrent calls to returnItem() or concurrent calls to removeItem() and returnItem().

Noncompliant Code Example (volatile)

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

Code Block
bgColor#FFcccc
public class InventoryManager {

  private static final int MIN_INVENTORY = 3;
  private volatile int itemsInInventory = 100;

  public final void removeItem() {
  if  if (itemsInInventory ><= MIN_INVENTORY) {
    return itemsInInventory--;  // Returns throw new count of items in inventory
IllegalStateException("under stocked");
    }
  else {
    underStocked() itemsInInventory--;
  }
}

public final void returnItem() {
  if (itemsInInventory > MAX_INVENTORY) { 
    overStocked();
  }
  else {
    return itemsInInventory++;
  }
}

Volatile variables are 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 still possible.

...

The java.util.concurrent utilities can be used to atomically manipulate a shared variable. This compliant solution uses defines intemsInInventory as a java.util.concurrent.atomic.AtomicInteger variable which allows , allowing composite operations to be performed atomically.

Code Block
bgColor#ccccff
privatepublic final class InventoryManager {

  private static final int MIN_INVENTORY = 3;
  private final AtomicInteger itemsInInventory = new AtomicInteger(100);

  private final int removeItem() {
    for (;;) {
      int old = itemsInInventory.get();
      if (old > 0MIN_INVENTORY) {
        int next = old - 1; // Decrement
        if (itemsInInventory.compareAndSet(old, next)) {
          return next;  // Returns new count of items in inventory
        }
      } else {
      return -1; //throw Error code
 new IllegalStateException("under stocked");
      }
    } // end for
  } // end removeItem()
} 

Note that updates to shared atomic variables become instantly are visible to other threads when this approach is used.

Wiki Markup
According to the Java API \[[API 06|AA. Java References#API 06]\], class {{AtomicInteger}} documentation:

Wiki Markup
\[AtomicInteger is an\] {{int}} value that may be updated atomically. An {{AtomicInteger}} is used in applications such as atomically incremented counters, and cannot be used as a replacement for an {{Integer}}. However, this class does extend {{Number}} to allow uniform access by tools and utilities that deal with numerically-based classes.

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 {{for}} loop guarantees the same behavior of the original function, namely that the function succeeds in decrementing {{itemsInInventory}} or an error code is returned.

The returnItem() method can be fixed by using the java.util.concurrent.atomic.AtomicInteger.getAndIncrement() method.

Code Block
bgColor#ccccff

public final int returnItem() {
  int temp = itemsInInventory.getAndIncrement();
  if (temp == Integer.MIN_VALUE) { // Check for integer overflow
    return -1;
  }
  return temp;
}

The getAndIncrement() does not check for integer overflow. Consequently, returnItem() has to check the returned value to ensure that itemsInInventory has not wrapped around to Integer.MIN_VALUE after the increment operation. This can be done after performing the getAndIncrement() operation.

Notably, this functionality could also be implemented by using the compareAndSet() method. The getAndIncrement() alternative is useful when control over setting the returned value must lie in the hands of the caller instead of the invoked method (returnItem()).

Compliant Solution (method synchronization)

Synchronization provides a way to safely share object state across multiple threads without the need to reason about reorderings, compiler optimizations, and hardware specific behavior.

This compliant solution uses method synchronization to synchronize access to itemsInInventory. Consequently, access to itemsInInventory is mutually exclusive and its state consistent across all threads.

Code Block
bgColor#ccccff

private int itemsInInventory = 100;

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

public synchronized final int returnItem() {
  if (itemsInInventory == Integer.MIN_VALUE) { // Check for integer overflow
    return -1;
  }
  return itemsInInventory++;
}

If code is synchronized correctly, updates to shared variables are instantly made visible to other threads. Synchronization is more expensive than using the optimized java.util.concurrent utilities and should generally be preferred when it is sufficiently complex to carry out the operation atomically using the utilities. When synchronizing, care must be taken to avoid deadlocks (see CON12-J. Avoid deadlock by requesting and releasing locks in the same order).

Compliant Solution (block synchronization)

Constructors and methods can use an alternative representation called block synchronization which synchronizes a block of code rather than a method, as highlighted in this compliant solution.

Code Block
bgColor#ccccff

private int itemsInInventory = 100;

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

public final int returnItem() {
  synchronized(this) {
    if (itemsInInventory == Integer.MIN_VALUE) { // Check for integer overflow
      return -1;
    }
    return itemsInInventory++;
  }
}

Similarly, the returnItem() method can be fixed by using block synchronization.

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 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).

When the number of items is 0 most of the time, the synchronized block may be moved inside the if condition to reduce the performance cost associated with synchronization. In that case, the variable itemsInInventory must be declared as volatile because the check to determine whether it is greater than 0 should rely on the latest value of itemsInInventory.

Compliant Solution (ReentrantLock)

This compliant solution uses a java.util.concurrent.locks.ReentrantLock to atomically perform the post-decrement operation.

Code Block
bgColor#ccccff

private int itemsInInventory = 100;
private final Lock lock = new ReentrantLock();

public int removeItem() {
  Boolean myLock = false;

  try {
    myLock = lock.tryLock();

    if (itemsInInventory > 0) {
      return itemsInInventory--;
    }
  } finally {
    if (myLock) {
      lock.unlock();
    }
  }
  return -1; // Error code
}

Similarly, the returnItem() method can be made atomic:

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 {{for}} loop guarantees the same behavior of the original function, namely that the function succeeds in decrementing {{itemsInInventory}} or an error code is returned.

Compliant Solution (method synchronization)

Synchronization provides a way to safely share object state across multiple threads without the need to reason about reorderings, compiler optimizations, and hardware specific behavior.

This compliant solution uses method synchronization to synchronize access to itemsInInventory. Consequently, access to itemsInInventory is mutually exclusive and its state consistent across all threads.

Code Block
bgColor#ccccff

public class InventoryManager {

  private static final int MIN_INVENTORY = 3;
  private int itemsInInventory = 100;

  public final synchronized void removeItem() {
    if (itemsInInventory <= MIN_INVENTORY) {
      throw new IllegalStateException("under stocked");
    }
    itemsInInventory--;
  }
} 

If code is synchronized correctly, updates to shared variables are instantly made visible to other threads. Synchronization is more expensive than using the optimized java.util.concurrent utilities and should generally be preferred when it is sufficiently complex to carry out the operation atomically using the utilities. When synchronizing, care must be taken to avoid deadlocks (see CON12-J. Avoid deadlock by requesting and releasing locks in the same order).

Compliant Solution (block synchronization)

Constructors and methods can use an alternative technique called block synchronization which synchronizes a block of code rather than a method, as shown in this compliant solution.

Code Block
bgColor#ccccff

public class InventoryManager {

  private static final int MIN_INVENTORY = 3;
  private int itemsInInventory = 100;

  public final synchronized void removeItem() {
    synchronized(this) {
      if (itemsInInventory <= MIN_INVENTORY) {
        throw new IllegalStateException("under stocked");
      }
      itemsInInventory--;
    }
  }
} 

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 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).

Compliant Solution (ReentrantLock)

This compliant solution uses a java.util.concurrent.locks.ReentrantLock to atomically perform the post-decrement operation.

Code Block
bgColor#ccccff

public class InventoryManager {

  private static final int MIN_INVENTORY = 3;
  private int itemsInInventory = 100;
  private final Lock lock = new ReentrantLock();

  public final synchronized void removeItem() {
  
Code Block
bgColor#ccccff

public int returnItem() {
  Boolean myLock = false;

    try {
      myLock = lock.tryLock();

      if (itemsInInventory =<= Integer.MIN_VALUEINVENTORY) {
 // Check for integer overflow
   throw new  return -1IllegalStateException("under stocked");
      }
     return itemsInInventory++--;
    } finally {
      if (myLock) {
        lock.unlock();
      }
    }

  return -1;} // Errorend coderemoveItem()
} 

Code that uses this lock behaves similar 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.

...