Declaring a shared mutable variable volatile
ensures the visibility of the latest updates on it, across other threads but does not guarantee the atomicity of composite operations. For example, the variable increment operation consisting of the sequence read-modify-write is not atomic even when the variable is declared volatile
. In such cases, the java.util.concurrent
utilities must be used to atomically manipulate the variable. If the utilities do not provide the required atomic methods, accesses to the variable must be explicitly synchronized.
Noncompliant Code Example
In this noncompliant code example, the field itemsInInventory
can be accessed by multiple threads. However, when a thread is updating the value of itemsInInventory
, it is possible for other threads to read the original value, before the update. This is because the post decrement operator is non-atomic.
private int itemsInInventory = 100; public int removeItem() { if(itemsInInventory > 0) { return itemsInInventory--; // Returns new count of items in inventory } else { return 0; } }
Compliant Solution (1)
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 java.util.concurrent.atomic.AtomicInteger
variable. According to the Java API [[API 06]], Class AtomicInteger
documentation:
[AtomicInteger is] An
int
value that may be updated atomically. AnAtomicInteger
is used in applications such as atomically incremented counters, and cannot be used as a replacement for anInteger
. However, this class does extendNumber
to allow uniform access by tools and utilities that deal with numerically-based classes.
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]]
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 0; } } } }
Compliant Solution (2)
This compliant solution uses method synchronization to synchronize access to shared variables. Consequently, access to itemsInInventory
is mutually exclusive and consistent across object states.
private int itemsInInventory = 100; public synchronized int removeItem() { if(itemsInInventory > 0) { return itemsInInventory--; // Returns new count of items in inventory } else { return 0; } }
Synchronization is more expensive than using the optimized java.util.concurrent
utilities and should only be used when the utilities do not contain the 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]]. Failure to follow this advice results in deadlocks ([CON11-J. Avoid deadlock by requesting locks in the proper order]).
Compliant Solution (2)
Constructors and methods can make use of an alternative representation called block synchronization which synchronizes a block of code rather than a method, as highlighted below.
private volatile int itemsInInventory = 100; public int removeItem() { if(itemsInInventory > 0) { synchronized(this) { return itemsInInventory--; // Returns new count of items in inventory } } else { return 0; } }
Block synchronization is preferable because it reduces the period for which the lock is held. 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 is more costly.
Risk Assessment
If access to shared, mutable variables is not synchronized, 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.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
CON01- J |
medium |
probable |
medium |
P8 |
L2 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[API 06]] Class AtomicInteger
[[JLS 05]] Chapter 17, Threads and Locks, section 17.4.5 Happens-before Order, section 17.4.3 Programs and Program Order, section 17.4.8 Executions and Causality Requirements
[[Tutorials 08]] Java Concurrency Tutorial
[[Lea 00]] Sections, 2.2.7 The Java Memory Model, 2.2.5 Deadlock, 2.1.1.1 Objects and locks
[[Bloch 08]] Item 66: Synchronize access to shared mutable data
[[Daconta 03]] Item 31: Instance Variables in Servlets
[[JavaThreads 04]] Section 5.2 Atomic Variables
[[MITRE 09]] CWE ID 667 "Insufficient Locking", CWE ID 413 "Insufficient Resource Locking", CWE ID 366 "Race Condition within a Thread", CWE ID 567 "Unsynchronized Access to Shared Data"
11. Concurrency (CON) 11. Concurrency (CON) CON01-J. Always synchronize on the appropriate object