According to the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\], Section 8.3.1.4, "{{volatile}} Fields"
{quote}
A field may be declared {{volatile}}, in which case the Java memory model (§17) ensures that all threads see a consistent value for the variable.
{quote}
Notably, thisThis visibility guarantee applies only to primitive fields and immutableobject member objectsreferences. TheProgrammers visibilitycommonly guaranteeuse doesimprecise notterminology, extendand to non-thread-safe mutable objects, even if their references are declared {{volatile}}. A thread may not observe a recent write from another thread to a member field of such an object. Declaring an object volatile to ensure visibility of its state does not work without the use of synchronization, unless the object is [immutable|BB. Definitions#immutable]. If the object is mutable and not thread-safe, other threads might see a partially constructed object or an object speak about "member objects." For the purposes of this visibility guarantee, the actual member is the object reference; the objects referred (the _referents_, hereafter) to by volatile object references are beyond the scope of the visibility guarantee. Consequently, declaring a member reference to be volatile is insufficient to guarantee that changes to the members of the referent are visible. That is, a thread may fail to observe a recent write from another thread to a member field of such a referent. Further, when the referent is mutable and lacks thread-safety, other threads might see a partially constructed object or an object in a (temporarily) inconsistent state \[[Goetz 2007|AA. Bibliography#Goetz 07]\].
Technically, However, when the object does not have to be strictly immutable to be used safely. If it can be determined that a member object is thread-safe by design, the field that holds its reference may be declared volatile. However, this approach to using volatile decreases maintainability and should be avoided.referent is [immutable|BB. Definitions#immutable], declaring the reference volatile suffices to guarantee visibility of the members of the referent. Consequently, use of the {{volatile}} keyword to guarantee visibility to mutable objects is forbidden; use of the {{volatile}} keyword to guarantee visibility to primitive fields, to object references, or to fields of immutable objects referents is permitted.
h2. Noncompliant Code Example (Arrays)
This noncompliant code example showsdeclares ana arrayvolatile objectreference thatto isan declaredarray volatileobject.
{code:bgColor=#FFcccc}
final class Foo {
private volatile int[] arr = new int[20];
public int getFirst() {
return arr[0];
}
public void setFirst(int n) {
arr[0] = n;
}
// ...
}
{code}
Values assigned to an array element by one thread, for example, by calling {{setFirst()}}, might not be visibleinvisible to another thread calling {{getFirst()}}, because the {{volatile}} keyword makes only makes the array reference visible; andit doesfails notto affecteffect the actual data contained within the array.
The problemroot occursof becausethe thereproblem is no [happens-before|BB. Definitions#happens-before order] relationship between that the thread that calls {{setFirst()}} and the thread that calls {{getFirst()}}. lack Aa [happens-before|BB. Definitions#happens-before order] relationship. A happens-before relationship exists between a thread that _writes_ to a volatile variable and a thread that _subsequently reads_ it. However, this code is neither writing to nor reading {{setFirst()}} and {{getFirst()}} only read from a volatile variable.
h2. Compliant Solution ({{ --- the volatile reference to the array; neither method writes to the volatile variable.
h2. Compliant Solution ({{AtomicIntegerArray}})
To ensure that the writes to array elements are atomic and that the resulting values are visible to other threads, this compliant solution uses the {{AtomicIntegerArray}} class defined in {{java.util.concurrent.atomic}}.
{code:bgColor=#ccccff}
final class Foo {
private final AtomicIntegerArray atomicArray = new AtomicIntegerArray(20);
public int getFirst() {
return atomicArray.get(0);
}
public void setFirst(int n) {
atomicArray.set(0, 10);
}
// ...
}
{code}
{{AtomicIntegerArray}} guarantees a [happens-before|BB. Definitions#happens-before order] relationship between a thread that calls {{atomicArray.set()}} and a thread that subsequently calls {{atomicArray.get()}}.
h2. Compliant Solution (Synchronization)
To ensure visibility, accessor methods may synchronize access, while performing operations on non-volatile elements of an array, thatwhether it is declared volatile referred to by a volatile or a non-volatile reference. Note that the code is thread-safe, even though the array reference is non-volatile.
{code:bgColor=#ccccff}
final class Foo {
private int[] arr = new int[20];
public synchronized int getFirst() {
return arr[0];
}
public synchronized void setFirst(int n) {
arr[0] = n;
}
}
{code}
Synchronization establishes a [happens-before|BB. Definitions#happens-before order] relationship between the threadthreads that calls {synchronize on the same lock. In this case, the thread that calls {{setFirst()}} and the thread that subsequently calls {{getFirst()}} both synchronize on the {{Foo}} instance, guaranteeingso visibility is guaranteed.
h2. Noncompliant Code Example (Mutable Object)
This noncompliant code example declares the {{Properties}} instance field volatile. The instance of the {{Properties}} object can be mutated using the {{put()}} method; consequently, andit thatis makesa the {{properties}} field mutablemutable object.
{code:bgColor=#FFcccc}
final class Foo {
private volatile Properties properties;
public Foo() {
properties = new Properties();
// Load some useful values into properties
}
public String get(String s) {
return properties.getProperty(s);
}
public void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
properties.setProperty(key, value);
}
}
{code}
Interleaved calls to {{get()}} and {{put()}} may result in internally inconsistent values being retrieved from the {{Properties}} object because the operations within {{put()}} modify its state. Declaring the object reference volatile doesis insufficient notto eliminate this data race.
There is noThe {{put()}} method lacks a time-of-check-time-of-use (TOCTOU) vulnerability in {{put()}}, despite the presence of the validation logic, because the validation is performed on the immutable {{value}} argument andrather than noton the shared {{Properties}} instance.
h2. Noncompliant Code Example (Volatile-Read, Synchronized-Write)
This noncompliant code example attempts to use the volatile-read, synchronized-write technique described by Goetz \[[Goetz 2007|AA. Bibliography#Goetz 07]\]. The {{properties}} field is declared volatile to synchronize its reads and writes. The {{put()}} method is also synchronized to ensure that its statements are executed atomically.
{code:bgColor=#ffcccc}
final class Foo {
private volatile Properties properties;
public Foo() {
properties = new Properties();
// Load some useful values into properties
}
public String get(String s) {
return properties.getProperty(s);
}
public synchronized void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
properties.setProperty(key, value);
}
}
{code}
The volatile-read, synchronized-write technique uses synchronization to preserve atomicity of compound operations, such as increment, and provides faster access times for atomic reads. However, it does not work with mutable objects because the visibility guarantee ofprovided by {{volatile}} objectextends referencesonly doesto notthe extendfield toitself object(the members. Consequently, thereprimitive value or object reference); the referent (and hence the referent's members) is no [happens-before|BB. Definitions#happens-before order] relationship betweenexcluded from the guarantee. Consequently, the write and a subsequent read of the property.
This technique is also discussed inlack a [VNA02-happens-before|BB. Definitions#happens-before order] relationship.
This technique is also discussed in [VNA02-J. Ensure that compound operations on shared variables are atomic].
h2. Compliant Solution (Synchronized)
This compliant solution uses method synchronization to guarantee visibility.
{code:bgColor=#ccccff}
final class Foo {
private final Properties properties;
public Foo() {
properties = new Properties();
// Load some useful values into properties
}
public synchronized String get(String s) {
return properties.getProperty(s);
}
public synchronized void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
properties.setProperty(key, value);
}
}
{code}
TheIt is unnecessary to declare the {{properties}} field does not need to be volatile because the accessor methods are synchronized. The field is declared final to prevent sopublication thatof its reference iswhen notthe publishedreferent when it is in a partially initialized state (see rule [TSM03-J. Do not publish partially initialized objects] for more information).
h2. Noncompliant Code Example (Mutable Sub-Object)
In this noncompliant code example, the volatile {{format}} field is used to store stores a reference to a mutable object, {{java.text.DateFormat}}.
{code:bgColor=#FFcccc}
final class DateHandler {
private static volatile DateFormat format=
DateFormat.getDateInstance(DateFormat.MEDIUM);
public static java.util.Date parse(String str) throws ParseException {
return format.parse(str);
}
}
{code}
Because {{DateFormat}} is not thread-safe \[[API 2006|AA. Bibliography#API 06]\], the value for {{parse()Date}} methodreturned might return a value forby the {{Dateparse()}} thatmethod might doesfail notto correspond to the {{str}} argument.
{mc}
// Calls DateHandler, demo code
public class DateCaller implements Runnable {
public void run(){
try {
System.out.println(DateHandler.parse("Jan 1, 2010"));
} catch (ParseException e) {
}
public static void main(String[] args) {
for(int i=0;i<10;i++)
new Thread(new DateCaller()).start();
}
}
{mc}
h2. Compliant Solution (Instance Per Call/Defensive Copying)
This compliant solution creates and returns a new {{DateFormat}} instance for everyeach invocation of the {{parse()}} method. \[[API 2006|AA. Bibliography#API 06]\]
{code:bgColor=#ccccff}
final class DateHandler {
public static java.util.Date parse(String str) throws ParseException {
return DateFormat.getDateInstance(DateFormat.MEDIUM).parse(str);
}
}
{code}
This solution doescomplies notwith violate rule [OBJ09-J. Defensively copy private mutable class members before returning their references] because the class no longer contains internal mutable state.
h2. Compliant Solution (Synchronization)
This compliant solution synchronizes statements within themakes {{parse()DateHandler}} method, makingthread-safe by synchronizing statements within the {{DateHandlerparse()}} thread-safemethod \[[API 2006|AA. Bibliography#API 06]\].
{code:bgColor=#ccccff}
final class DateHandler {
private static DateFormat format=
DateFormat.getDateInstance(DateFormat.MEDIUM);
public static java.util.Date parse(String str) throws ParseException {
synchronized (format) {
return format.parse(str);
}
}
}
{code}
h2. Compliant Solution ({{ThreadLocal}} Storage)
This compliant solution uses a {{ThreadLocal}} object to create a separate {{DateFormat}} instance per thread.
{code:bgColor=#ccccff}
final class DateHandler {
private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>() {
@Override protected DateFormat initialValue() {
return DateFormat.getDateInstance(DateFormat.MEDIUM);
}
};
// ...
}
{code}
DateHandler {
private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>() {
@Override protected DateFormat initialValue() {
return DateFormat.getDateInstance(DateFormat.MEDIUM);
}
};
// ...
}
{code}
h2. Exceptions
*VNA06-EX1*: Technically, strict immutability of the referent is a stronger condition than is fundamentally required for safe visibility. When it can be determined that a referent is thread-safe by design, the field that holds its reference may be declared volatile. However, this approach to using volatile decreases maintainability and should be avoided.
h2. Risk Assessment
Incorrectly assuming that declaring a field volatile guarantees that the visibility of a referenced object's members can cause threads to observe stale or inconsistent values.
|| Guideline || Severity || Likelihood || Remediation Cost || Priority || Level ||
| VNA06-J | medium | probable | medium | {color:#cc9900}{*}P8{*}{color} | {color:#cc9900}{*}L2{*}{color} |
h3. Automated Detection
TODO
h3. Related Vulnerabilities
Any vulnerabilities resulting from the violation of this rule are listed on the [CERT website|https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+CON11-J].
h2. Bibliography
-J].
h2. Bibliography
\[[API 2006|AA. Bibliography#API 06]\] Class {{java.text.DateFormat}}
\[[Goetz 2007|AA. Bibliography#Goetz 07]\] Pattern #2: "one-time safe publication"
\[[MillerJLS 20092005|AA. Bibliography#MillerBibliography#JLS 0905]\] Mutable Statics
\[[APIMiller 20062009|AA. Bibliography#APIBibliography#Miller 0609]\] Class {{java.text.DateFormat}}
\[[JLS 2005|AA. Bibliography#JLS 05]\]Mutable Statics
----
[!The CERT Oracle Secure Coding Standard for Java^button_arrow_left.png!|VNA05-J. Ensure atomicity when reading and writing 64-bit values] [!The CERT Oracle Secure Coding Standard for Java^button_arrow_up.png!|07. Visibility and Atomicity (VNA)] [!The CERT Oracle Secure Coding Standard for Java^button_arrow_right.png!|08. Locking (LCK)]
|