Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: general edit

...

Wiki Markup
"Sequential consistency and/or freedom from data races still allows errors arising from groups of operations that need to be perceived atomically and are not." \[[JLS 05|AA. Java References#JLS 05]\]. In such cases, the {{java.util.concurrent}} utilities must be used to atomically manipulate a shared variable. If the utilities do not provide the required atomic methods, operations that use the variable mustshould be correctly synchronized. 

Note that, as with volatile, updated values are immediately visible to other threads when either one of these two techniques is used. Synchronization provides a way to safely share object state across multiple threads without the need to reason about reorderingreorderings, compiler optimizations and hardware specific behavior.

...

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

...

Volatile variables are unsuitable when more than one load/store operation needs to be atomic. There is an alternative method to perform multiple operations atomically. This compliant solution shows a {{uses a java.util.concurrent.atomic.AtomicInteger}} variable. 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 to the given updated value if and only if the current value equals the expected value. \[[API 06|AA. Java References#API 06]\] 

...

bgColor#ccccff

Code Block
bgColor#ccccff

public class Sync {
  private final AtomicInteger itemsInInventory = new AtomicInteger(100);

  private int removeItem() {
    for (;;) {
      int old = itemsInInventory.get();
      if (old > 0) {
        int next = old - 1;
        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:

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 to the given updated value if and only if the current value equals the expected value. \[[API 06|AA. Java References#API 06]\] 

...

Compliant Solution (2) (method synchronization)

This compliant solution uses method synchronization to synchronize access to shared variables. Consequently, access to itemsInInventory is mutually exclusive and consistent across all object states.

Code Block
bgColor#ccccff
private int itemsInInventory = 100;

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

Wiki Markup
Synchronization is more expensive than using the optimized {{java.util.concurrent}} utilities and should only be used when the utilities do not contain the the facilities (methods) required method to carry out the atomic operation. When using explicit synchronization, the programmer must also ensure that two or more threads are not mutually accessible from a different set of two or more threads such that each thread holds a lock while trying to obtain another lock that is held by the other thread \[[Lea 00|AA. Java References#Lea 00]\]. Failure to follow this advice results in deadlocks ([CON12-J. Avoid deadlock by requesting and releasing locks in the same order]).

...

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

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

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

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. The variable itemsInInventory still needs , though the latter requires synchronizing on a private lock object instead of the this reference.

If the synchronized block was moved inside the if condition to reduce the performance cost associated with synchronization, the variable itemsInInventory would be required to be declared as 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.

Compliant Solution (4) (ReentrantLock)

...

This noncompliant code example uses two AtomicReference objects to hold two one BigInteger object referencesreference each.

Code Block
bgColor#FFcccc
public class AtomicAdder {
  private final AtomicReference<BigInteger> first;	
  private final AtomicReference<BigInteger> second; 

  public AtomicAdder(BigInteger f, BigInteger s) {
    first  = new AtomicReference<BigInteger>(f);
    second = new AtomicReference<BigInteger>(s);
  }

  public void update(BigInteger f, BigInteger s){ // Unsafe
    first.set(f);
    second.set(s);
  }

  public BigInteger add() { // Unsafe
    return first.get().add(second.get()); 
  }
}

An AtomicReference is an object reference that can be updated atomically. Operations that use these two atomic references independently are guaranteed to be atomic, however, if an operation involves using both together, thread-safety issues arise. For instance, in this noncompliant code example, adding the two big integers is not thread-safe because it is possible that while the addition is being carried out in a thread, another thread may update the value of one or both big integers, leading to an erroneous result.

...

Prefer using the block form of synchronization for better performance, when there are nonatomic operations within the method that do not require any synchronization. These operations can be decoupled from those that require synchronization and executed outside the synchronized block.

Risk Assessment

If operations on shared variables are not atomic, unexpected results may be produced. For example, there can be inadvertent information disclosure as one user may be able to receive information about other users.

...