Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: initial edits...

A consistent locking policy guarantees that no two multiple threads can cannot simultaneously access or modify some shared data. In the absence of such a policy, 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 resultto introduce a data race. If two or more operations need to be performed as a single atomic operation, it is necessary to implement a consistent locking policy by either using intrinsic synchronization or the java.util.concurrent utilities.

In presence of Given an invariant involving two multiple objects, it is tempting to believe that if operations on the two objects are individually atomic, a programmer may incorrectly assume that individually atomic operations require no additional locking is required; however this is not the case.

Similarly, programmers sometimes incorrectly assume that using a thread-safe Collection does not require explicit synchronization to preserve an invariant that involves the collection's elements. A thread-safe class can only guarantee atomicity of its individual methods. A grouping of calls to such methods requires additional synchronization.

For instanceexample, consider a scenario where the standard thread-safe API does not provide a method to both find a particular person's record in a Hashtable and also update the corresponding payroll information. In such cases, a custom atomic method must be designed and used. This guideline discusses the rationale behind using such a method and provides the relevant implementation advice.

...

Expressions involving compound operators are also non-atomic. Refer to CON01-J. Ensure that compound operations on shared variables are atomic for more information.

Noncompliant Code Example (AtomicReference)

This noncompliant code example uses two wraps BigInteger objects within thread-safe AtomicReference objects that wrap one BigInteger object each.

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

  public Adder(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 two atomic references independently, are guaranteed to be atomic, however, if an operation involves using both together, thread-safety issues arisethe resulting combined operation is not atomic. In this noncompliant code example, one thread may call update() while a second thread may call add(). This might cause the add() method to add the new value of first to the 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.

...

Prefer using block synchronization instead of method synchronization when the method contains non-atomic operations that either do not require any synchronization or can use a more fine-grained locking scheme involving multiple internal private lock objects. Non-atomic operations can be decoupled from those that require synchronization and executed outside the synchronized block. The guideline CON04-J. Synchronize using an internal private final lock object has more details on using private internal lock objects and block synchronization.

Noncompliant Code Example (synchronizedList)

This noncompliant code example is comprised of has a java.util.ArrayList<E> collection which is not thread-safe by default. However, most classes that are not thread-safe have a synchronized thread-safe version, for example, the Collections.synchronizedList is used as a good substitute synchronization wrapper for ArrayList and Collections.synchronizedMap is a good alternative to HashMap.

Code Block
bgColor#FFCCCC
final class IPHolder {
  private final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>());
  
  public void addIPAddress(InetAddress address) {
    // Validate address
    ips.add(address);
  }
  
  public void addAndPrintIP(InetAddress address) {
    addIPAddress(address);
    InetAddress[] ia = (InetAddress[]) ips.toArray(new InetAddress[0]);      
    System.out.println("Number of IPs: " + ia.length);     
  }
}

Even though the Collection wrapper offers thread-safety guarantees, atomicity related issues manifest themselves when calling methods of the class. When the addAndPrintIP() method is invoked on the same object from multiple threads, the output which consists of varying array lengths, may indicate a race condition between the threads. The statements in method addAndPrintIP() that are responsible for adding an IP address and printing out the length of the list, are not sequentially consistent.

Compliant Solution (Synchronized block)

To eliminate the race condition, ensure atomicity by using the underlying list's lock. This can be achieved by including all statements that use the array list within a synchronized block that locks on the list.

...

This code does not violate CON40-J. Do not synchronize on a collection view if the backing collection is still accessible, because while it does synchronize on a collectoin view (the synchronizedList), the backing collection is not accessible, and hence cannot be modified by any code.

Noncompliant Code Example (synchronizedMap)

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

...

Note that while this code is thread-unsafe, it at least prevents integer overflow when incrementing the map values, as mandated by INT00-J. Perform explicit range checking to ensure integer operations do not overflow.

Compliant Solution (synchronized blocks)

To ensure atomicity, this compliant solution uses an internal private lock object to synchronize the statements of the increment() and getCount() methods.

...

This compliant solution does not use Collections.synchronizedMap() because locking on the (unsynchronized) map provides sufficient thread-safety for this application. The guideline CON40-J. Do not synchronize on a collection view if the backing collection is still accessible provides more information about synchronizing on synchronizedMap objects.

Compliant Solution (ConcurrentHashMap)

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

...

Note that methods such as size() and isEmpty() are allowed to return an approximate result for performance reasons. Code should not rely on these return values for deriving exact results.

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]\] 
\[[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, 5.2.1. ConcurrentHashMap
\[[Lee 09|AA. Java References#Lee 09]\] "Map & Compound Operation"

...