Versions Compared

Key

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

Thread-safety A consistent locking policy guarantees that no two multiple threads can cannot simultaneously access or modify some shared data. However, if When two or more operations need to must be performed as a single large atomic operation, it becomes necessary to add additional locking in order to enforce atomicity. It is possible for two threads to read some shared value, independently perform operations on it and induce a race condition while storing the final result.a consistent locking policy must be implemented using either intrinsic synchronization or java.util.concurrent utilities. In the absence of such a policy, the code is susceptible to race conditions.

When presented with a set of operations, where each is guaranteed to be atomicIf an invariant exists involving two objects, it is tempting to believe that if the objects are atomic, no additional locking is required; however this is not the case. Likewise, programmers sometimes assume that using assume that a single operation consisting of individually atomic operations is guaranteed to be collectively atomic without additional locking. Similarly, programmers might incorrectly assume that use of a thread-safe Collection does not require explicit synchronization in order is sufficient to preserve an invariant involving that involves the collection's elements . Any object that guarantees atomicity without additional synchronization. A thread-safe class can only guarantee atomicity over the of its individual methods it promises to be thread-safe.. A grouping of calls to such methods requires additional synchronization for the group.

Consider, for example, a scenario in which For example, the standard thread-safe API may not provide lacks a single method both to both find a particular person's record in a Hashtable and also update the corresponding to update that person's payroll information. In such cases, a custom atomic the two method invocations must be designed and used. This guideline shows the need of such a method to perform a group of independently atomic operations as one atomic operation, and also suggests techniques for incorporating the method using a custom API.

This guideline applies to all uses of Collection classes including the thread-safe Hashtable class. Enumerations of the objects of a Collection and iterators also require explicit synchronization on the Collection object or any single lock object.

performed atomically.

Enumerations and iterators also require either explicit synchronization on the collection object (client-side locking) or use of a private final lock object.

Compound operations on shared variables are also non-atomic (see VNA02-J. Ensure that compound operations on shared variables are atomic for more information).

VNA04-J. Ensure that calls to chained methods are atomic describes a specialized case of this ruleSome primitive operators may also not be atomic; see CON01-J. Ensure that compound operations on shared variables are atomic for more information.

Noncompliant Code Example (AtomicReference)

This noncompliant code example uses two AtomicReference objects to hold one BigInteger object reference each. wraps references to BigInteger objects within thread-safe AtomicReference objects:

Code Block
bgColor#FFcccc

final class AtomicAdderAdder {
  private final AtomicReference<BigInteger> first;	
  private final AtomicReference<BigInteger> second; 

  public AtomicAdderAdder(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, one thread could However, operations that combine more than one atomic reference are non-atomic. In this noncompliant code example, one thread may call update() while a second thread calls may call add(), with the result that . This might cause the add() operation adds the newer method to add the new value of first to the older old value of second, yielding an erroneous result.

Compliant Solution (

...

Method Synchronization)

This compliant solution declares the update() and add() methods as synchronized to guarantee atomicity. :

Code Block
bgColor#ccccff

final class AtomicAdderAdder {
  // ...
  private final AtomicReference<BigInteger> first;
  private  public synchronized void updatefinal AtomicReference<BigInteger> second;

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



  public synchronized BigIntegervoid addupdate() BigInteger f, BigInteger s){
    first.set(f);
    second.set(s);
  }

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

Prefer using the block form of synchronization 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.

...

Noncompliant Code Example (synchronizedList())

This noncompliant code example comprises an ArrayList collection which is non-uses a java.util.ArrayList<E> collection, which is not thread-safe by default. However, most thread-unsafe classes have a synchronized thread-safe version, for example, the example uses Collections.synchronizedList is as a good substitute synchronization wrapper for the ArrayList and Collections.synchronizedMap is a good alternative to HashMap. The atomicity pitfall described in the coming lines, remains to be addressed even when the particular Collection offers thread-safety benefits. It subsequently uses an array, rather than an iterator, to iterate over the ArrayList to avoid a ConcurrentModificationException.

Code Block
bgColor#FFCCCC

final class RaceCollectionIPHolder {
  private final List<InetAddress> ips = 
      Collections.synchronizedList(new ArrayList<InetAddress>());
  
  public void addIPAddressaddAndPrintIPAddresses(InetAddress iaaddress) {
    // Validate ia
    ips.add(iaaddress);
  }
  
InetAddress[]  public void addAndPrintIP() throws UnknownHostException {
    addIPAddress(InetAddress.getLocalHost());
addressCopy = 
     InetAddress[] ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
    // Iterate 
through array addressCopy  System..out.println("Number
 of IPs: " + ia.length);     
  }
}
 }
}

Individually, the add() and toArray() collection methods are atomic. However, when called in succession (as shown in the addAndPrintIPAddresses() method), there is no guarantee that the combined operation is atomic. The addAndPrintIPAddresses() method contains a race condition that allows one thread to add to the list and a second thread to race in and modify the list before the first thread completes. Consequently, the addressCopy array may contain more IP addresses than expectedWhen the addAndPrintIP() method is invoked on the same object from multiple threads, the output, consisting of varying array lengths, may indicate a race condition between the threads. In other words, the statements in method addAndPrint() that are responsible for adding an IP address and printing it out are not sequentially consistent.

Compliant Solution (Synchronized

...

Block)

To eliminate the The race condition, ensure atomicity by using can be eliminated by synchronizing on the underlying list's lock. This can be achieved by including all statements that use compliant solution encapsulates all references to the array list within a synchronized block that locks on the list. synchronized blocks:

Code Block
bgColor#ccccff

final class RaceCollectionIPHolder {
  private final List<InetAddress> ips = 
      Collections.synchronizedList(new ArrayList<InetAddress>());

  public void addIPAddressaddAndPrintIPAddresses(InetAddress iaaddress) { 
    synchronized (ips) { 
      // Validate
      ips.add(iaaddress);
    }
  }

  public void addAndPrintIP() throws UnknownHostException {
    synchronized (ips) {
      addIPAddress(InetAddress.getLocalHost());
InetAddress[] addressCopy = 
        ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
      // Iterate through array addressCopy ...
      System.out.println("Number of IPs: " + ia.length); 
    }}
  }
}

...

This technique is also called client-side locking \ [[Goetz 06|AA. Java References#Goetz 06]\], because the class holds a lock on an object that presumably might be accessible to other classes. Goetz et al. \[[Goetz 06|AA. Java References#Goetz 06]\] caution against misuse of client-side locking:

If extending a class to add another atomic operation is fragile because it distributes the locking code for a class over multiple classes in an object hierarchy, client-side locking is even more fragile because it entails putting locking code for class C into classes that are totally unrelated to C. Exercise care when using client-side locking on classes that do not commit to their locking strategy.

Wiki Markup
Although expensive, {{CopyOnWriteArrayList}} and {{CopyOnWriteArraySet}} classes are sometimes used to create copies of the core {{Collection}} so that iterators do not fail with a runtime exception when some data in the {{Collection}} is modified. However, any updates to the {{Collection}} are not immediately visible to other threads. Consequently, their use is limited to boosting performance in code where the writes are fewer (or non-existent) as compared to the reads  \[[JavaThreads 04|AA. Java References#JavaThreads 04]\]. In all other cases they must be avoided (see [MSC13-J. Do not modify the underlying collection when an iteration is in progress]).    

Noncompliant Code Example (synchronizedMap)

Wiki Markup
This noncompliant code example defines a thread-unsafe {{KeyedCounter}} class. Even though the {{HashMap}} field is synchronized, the overall {{increment}} operation is not atomic. \[[Lee 09|AA. Java References#Lee 09]\]   

Goetz 2006] because the class holds a lock on an object that might be accessible to other classes. Client-side locking is not always an appropriate strategy (see LCK11-J. Avoid client-side locking when using classes that do not commit to their locking strategy for more information).

This code does not violate LCK04-J. Do not synchronize on a collection view if the backing collection is accessible because, although it synchronizes on a collection view (the synchronizedList result), the backing collection is inaccessible and consequently cannot be modified by any code.

Note that this compliant solution does not actually use the synchronization offered by Collections.synchronizedList(). If no other code in this solution used it, it could be eliminated.

Noncompliant Code Example (synchronizedMap())

This noncompliant code example defines the KeyedCounter class that is not thread-safe. Although the HashMap is wrapped in a synchronizedMap(), the overall increment operation is not atomic [Lee 2009].

Code Block
bgColor#FFCCCC
final class KeyedCounter {
  private final Map<String, Integer> map =
      Collections.synchronizedMap(new HashMap<String, Integer>());

  public void increment(String key) {
    Integer old = map.get(key);
    int oldValue = (old == null) ? 0 : old.intValue();
    if (oldValue == Integer.MAX_VALUE) {
      throw new ArithmeticException("Out of range");
    }
    map.put( key, oldValue + 1);
  }

  public Integer getCount(String key) {
    return map.get(key);
  }
}

Compliant Solution (Synchronization)

This compliant solution ensures atomicity by using an internal private lock object to synchronize the statements of the increment() and getCount() methods:

Code Block
bgColor#ccccff
final class KeyedCounter {
  private final Map<String, Integer> map =
      new HashMap<String, Integer>();
  private final Object lock = new Object();

  public void increment(String key) {
    synchronized (lock) {
      Integer old = map.get(key);
      int oldValue = (old == null) ? 0 : old.intValue();
      if (oldValue == Integer.MAX_VALUE) {
        throw new ArithmeticException("Out of range");
      }
      map.put(key, oldValue + 1);
    }
Code Block
bgColor#FFCCCC

public class KeyedCounter {
  private final Map<String, Integer> map =
    Collections.synchronizedMap(new HashMap<String, Integer>());

  public void increment(String key) {
    Integer old = map.get(key);
    int value = (old == null) ? 1 : old.intValue() + 1;
    map.put(key, value);
  }

  public Integer getCount(String key) {
    synchronized (lock) {
      return map.get(key);
    }
  }
}

...

This compliant solution uses a private object lock to synchronize the method bodies of the increment() and getCount methods, to ensure atomicity. For more information on private object locks, see CON04-J. Synchronize using an internal private lock object.avoids using Collections.synchronizedMap() because locking on the unsynchronized map provides sufficient thread-safety for this application. LCK04-J. Do not synchronize on a collection view if the backing collection is accessible provides more information about synchronizing on synchronizedMap() objects.

Compliant Solution (ConcurrentHashMap)

The previous compliant solution is safe for multithreaded use but does not scale because of excessive synchronization, which can lead to decreased performance.

The ConcurrentHashMap class used in this compliant solution provides several utility methods for performing atomic operations and is often a good choice for algorithms that must scale [Lee 2009].

Note that this compliant solution still requires synchronization, because without it, the test to prevent overflow and the increment will not happen atomically, so two threads calling increment() can still cause overflow. The synchronization block is smaller and does not include the lookup or addition of new values, so it has less impact on performance than the previous compliant solution.

Code Block
bgColor#ccccff
final class KeyedCounter {
  private final ConcurrentMap<String, AtomicInteger> map =
Code Block
bgColor#ccccff

public class KeyedCounter {
  private final Map<String,Integer> map = new HashMap<String,Integer>(); 
  private final Object lock = new Object();

  public void increment(String key) {
    synchronized (lock) {
      Integernew old = map.get(keyConcurrentHashMap<String, AtomicInteger>();
  private final Object lock int= valuenew = (old == null) ? 1 : old.intValue() + 1;Object();

  public void increment(String key) {
    AtomicInteger  map.put(key, valuevalue = new AtomicInteger();
    }
AtomicInteger old }

  public Integer getCount(String key) {= map.putIfAbsent(key, value);

    synchronizedif (lockold != null) {
      return map.get(key)value = old;
    }

    }
}

Also, note that this would be a violation of a previously discussed noncompliant code example if the field map were to refer to a Collections.synchronizedMap object. This compliant solution uses the intrinsic lock of the class for all purposes.

Compliant Solution (ConcurrentHashMap)

Wiki Markup
The previous compliant solution does not scale very well because a class with several {{synchronized}} methods can be potential bottleneck as far as acquiring locks is concerned and may further lead to contention or deadlock. The class {{ConcurrentHashMap}}, through a more preferable approach, provides several utility methods to perform atomic operations and is used in this compliant solution \[[Lee 09|AA. Java References#Lee 09]\]. 

Code Block
bgColor#ccccff

public class KeyedCounter {
  private final ConcurrentMap<String, AtomicInteger> map =
    new ConcurrentHashMap<String, AtomicInteger>();

  public void increment(String key) {
    AtomicInteger value = new AtomicInteger(0);
    AtomicInteger old = map.putIfAbsent(key, value);
   
    if (old != null) { 
      value = old; 
    }

    value.incrementAndGet(); // Increment the value atomically
  }

  public Integer getCount(String key) {
    AtomicInteger value = map.get(key);
    return (value == null) ? null : value.get();
  }
}

Wiki Markup
According to Goetz et al. \[[Goetz 06|AA. Java References#Goetz 06]\] section 5.2.1. ConcurrentHashMap:

ConcurrentHashMap, along with the other concurrent collections, further improve on the synchronized collection classes by providing iterators that do not throw ConcurrentModificationException, as a result eliminating the need to lock the collection during iteration. The iterators returned by ConcurrentHashMap are weakly consistent instead of fail-fast. A weakly consistent iterator can tolerate concurrent modification, traverses elements as they existed when the iterator was constructed, and may (but is not guaranteed to) reflect modifications to the collection after the construction of the iterator.

Risk Assessment

Non-atomic code can induce race conditions and affect program correctness.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON07- J

low

probable

medium

P4

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[API 06|AA. Java References#API 06]\] Class Vector, Class WeakReference
\[[JavaThreads 04|AA. Java References#JavaThreads 04]\] 8.2 "Synchronization and Collection Classes"
\[[Goetz 06|AA. Java References#Goetz 06]\] 4.4.1. Client-side Locking, 4.4.2. Composition and 5.2.1. ConcurrentHashMap
\[[Lee 09|AA. Java References#Lee 09]\] "Map & Compound Operation"

 synchronized (lock) {
      if (value.get() == Integer.MAX_VALUE) {
        throw new ArithmeticException("Out of range");
      }
      value.incrementAndGet(); // Increment the value atomically
    }
  }

  public Integer getCount(String key) {
    AtomicInteger value = map.get(key);
    return (value == null) ? null : value.get();
  }

  // Other accessors ...
}

According to Section 5.2.1., "ConcurrentHashMap," of the work of Goetz and colleagues [Goetz 2006]:

ConcurrentHashMap, along with the other concurrent collections, further improve on the synchronized collection classes by providing iterators that do not throw ConcurrentModificationException, as a result eliminating the need to lock the collection during iteration. The iterators returned by ConcurrentHashMap are weakly consistent instead of fail-fast. A weakly consistent iterator can tolerate concurrent modification, traverses elements as they existed when the iterator was constructed, and may (but is not guaranteed to) reflect modifications to the collection after the construction of the iterator.

Note that methods such as ConcurrentHashMap.size() and ConcurrentHashMap.isEmpty() are allowed to return an approximate result for performance reasons. Code should avoid relying on these return values when exact results are required.

Risk Assessment

Failure to ensure the atomicity of two or more operations that must be performed as a single atomic operation can result in race conditions in multithreaded applications.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

VNA03-J

Low

Probable

Medium

P4

L3

Automated Detection

Some static analysis tools are capable of detecting violations of this rule.

ToolVersionCheckerDescription
CodeSonar

Include Page
CodeSonar_V
CodeSonar_V

JAVA.CONCURRENCY.VOLATILEUseless volatile Modifier (Java)
Coverity7.5

ATOMICITY
GUARDED_BY_VIOLATION
INDIRECT_GUARDED_BY_VIOLATION
NON_STATIC_GUARDING_STATIC
NON_STATIC_GUARDING_STATIC
FB.IS2_INCONSISTENT_SYNC
FB.IS_FIELD_NOT_GUARDED
FB.IS_INCONSISTENT_SYNC
FB.STCAL_INVOKE_ON_STATIC_ CALENDAR_INSTANCE
FB.STCAL_INVOKE_ON_STATIC_ DATE_FORMAT_INSTANCE
FB.STCAL_STATIC_CALENDAR_ INSTANCE
FB.STCAL_STATIC_SIMPLE_DATE_ FORMAT_INSTANCE

Implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.VNA03.SSUG
CERT.VNA03.MRAV
Make the get method for a field synchronized if the set method is synchronized
Access related Atomic variables in a synchronized block
ThreadSafe
Include Page
ThreadSafe_V
ThreadSafe_V

CCE_CC_NON_ATOMIC_GCP
CCE_CC_NON_ATOMIC_CP
CCE_CC_UNSAFE_ITERATION
CCE_LK_REPLACE_WITH_TRYLOCK

Implemented

Related Guidelines

MITRE CWE

CWE-362, Concurrent Execution Using Shared Resource with Improper Synchronization ("Race Condition")
CWE-366, Race Condition within a Thread
CWE-662, Improper Synchronization

Bibliography

[API 2014]


[Goetz 2006]

Section 4.4.1, "Client-side Locking"
Section 5.2.1, "ConcurrentHashMap"

[JavaThreads 2004]

Section 8.2, Synchronization and Collection Classes

[Lee 2009]

Map & Compound Operation


...

Image Added Image Added VOID CON06-J. Do not defer a thread that is holding a lock      11. Concurrency (CON)      Image Modified