Section 8.3.1.4, "{{volatile}} Fields" of According to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\] states the following:, Section 8.3.1.4, "{{volatile}} Fields"
{quote}
A field may be declared {{volatile}}, in which case the Java memory model (§17§17) ensures that all threads see a consistent value for the variable.
{quote}
Notably, this applies only to primitive fields and immutable member objects. The visibility guarantee does not extend to non-thread-safe mutable objects that are not thread-safe, 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 in a (temporarily) inconsistent state \[[Goetz 07|AA. Java References#Goetz 07]\].
Technically, the object does not have to be strictly immutable to be used safely. If it can be proveddetermined that thea member object is thread-safe by design, the field that will holdholds its reference may be declared as {{volatile}}. However, this approach to using volatile burdensdecreases maintainability and should be avoided.
h2. Noncompliant Code Example (Arrays)
This noncompliant code example shows an array object (arrays are objects in Java) that is declared {{volatile}}.
{code:bgColor=#FFcccc}
final class Foo {
volatile private int[] arr = new int[20];
public int getFirst() {
return arr[0];
}
public void setFirst(int n) {
arr[0] = n;
}
// ...
}
{code}
The assumption that a value written Values assigned to an array element by one thread, is visible to other threads is incorrectfor example, becauseby thecalling {{volatilesetFirst()}}, keywordmay onlynot makes the be visible to another thread calling {{getFirst()}} because the {{volatile}} keyword only makes the array reference visible and does not affect the actual data contained within the array.
The Forproblem example,occurs whenbecause athere threadis assigns a new value to {{arr\[1\]}}, anotherno [happens-before|BB. Definitions#happens-before order] relation between the thread that is attempting to read the value of {{arr\[1\]}} might observe a stale value.
This happens because there is no [happens-before|BB. Definitions#happens-before order] relation between thecalls {{setFirst()}} and the thread that calls {{getFirst()}}. A happens-before relation exists between a thread that writes to a volatile variable and a thread that calls {{setFirst()}} and the thread that calls {{getFirst()}}. A happens-before relation exists between a thread that writes to a volatile variable and a thread that subsequently reads it. This code is neither writing to nor reading from a volatile variable. subsequently reads it. However, this code is neither writing to nor reading from a volatile variable.
h2. Compliant Solution ({{AtomicIntegerArray}})
This compliant solution uses the {{java.util.concurrent.atomic.AtomicIntegerArray}} class. Its {{set(index, value)}} method ensures that the write isto ensure that the writes to array elements are atomic and that the resulting valuevalues isare visible to other threads. The other threads can retrieve a value from a specific index using the {{get(index)}} method.
{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] relation between a thread that calls {{atomicArray.set()}} and a thread that subsequently calls {{atomicArray.get()}}. However, if a thread calls {{getFirst()}} first, it sees the default value of the atomic integer (0).
h2. Compliant Solution (Synchronization)
h2. Compliant Solution (Synchronization)
To ensure visibility, accessor methods may synchronize access, while performing operations on non-volatile elements of an array that is declared {{volatile}}. Note that the code is thread-safe, even though the array reference is not volatile.
{code:bgColor=#ccccff}
final class Foo {
private int[] arr = new int[20];
public synchronized int getFirst() {
return arr[1];
}
public synchronized void setFirst(int n) {
arr[1] = n;
}
}
{code}
Synchronization establishes a [happens-before|BB. Definitions#happens-before order] relation between the thread that calls {{setFirst()}} and the thread that subsequently calls {{getFirst()}}. Consequently, the array element set by {{setFirst()}} is guaranteed to be visible to {{getFirst()}}.
h2. Noncompliant Code Example guaranteeing visibility.
h2. Noncompliant Code Example (Mutable Object)
This noncompliant code example declares anthe instance field of the {{Properties}} type as {{volatile}}. The instance of the {{Properties}} object can be mutated using the {{put()}} method, and that makes the {{properties}} field mutable.
{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
properties.setProperty(key, value);
}
}if (!value.matches("[\\d\\w]*")) {
throw new IllegalArgumentException();
}
properties.setProperty(key, value);
}
{code}
IfInterleaved onecalls threadto calls {{get()}} whileand another calls {{put()}}, themay firstresult threadin mayinternally receiveinconsistent avalues stale or internally inconsistent valuebeing retrieved from the {{Properties}} object, because the operations within {{put()}} modify theits state of the {{Properties}} object instance. Declaring the object {{volatile}} does not preventeliminate this data race.
There is no 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 and not the shared {{Properties}} instance.
h2. Compliant Solution (Immutable)
This compliant solution renders the {{properties}} field immutable by not providing a {{put()}} method. Consequently, once it is properly constructed, no thread can modify the state of the {{Properties}} object instance and cause a data race.
{code:bgColor=#ccccff}
final class Foo {
private final Properties properties;
public Foo() {
properties = new Properties();
// Load some useful values into properties
}
public String get(String s) {
return properties.getProperty(s);
}
}
{code}
The {{Foo}} class is also [immutable|BB. Definitions#immutable], because all its fields are {{final}} and the {{properties}} field is being published safely. The disadvantage of making {{Foo}} immutable is that the
There is no time of check, time of use (TOCTOU) vulnerability in {{put()}}, method can no longer be accommodated. When that is unacceptable, the {{get()}} and {{put()}} methods must use some form of synchronization to prevent data racesdespite the presence of the validation logic, because the validation is performed on the immutable {{value}} argument and not 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 07|AA. Java References#Goetz 07]\]. The {{properties}} field is declared {{volatile}} to synchronize reads and writes of the field. 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
values before inserting
if (!value.matches("[\\d\\w]*")) {
// ...
throw new properties.setProperty(key, valueIllegalArgumentException();
}
}
{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 of {{volatile}} does not extend to their members. Consequently, if one thread adds a property using {{put}}, other threads may not observe this change. There work with mutable objects, because the visibility of {{volatile}} object references does not extend to object members. Consequently, there is no [happens-before relation|BB. Definitions#happens-before order] between the write and a subsequent read of the property.
This technique is also discussed in [ the property.
This technique is also discussed in [CON01-J. Ensure that compound operations on shared variables are atomic|CON01-J. Ensure that compound operations on shared variables are atomic].
h2. Compliant Solution (Synchronized)
This compliant solution uses method synchronization to ensureguarantee thread-safetyvisibility.
{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
properties.setProperty(key, value);
}
before inserting
if (!value.matches("[\\d\\w]*")) {
throw new IllegalArgumentException();
}
{code}
NoteThe that the {{properties}} field isdoes not declared {{volatile}},need to be volatile because thisthe solutionmethods achieves thread-safety using synchronizationare synchronized. The field is declared {{final}} so that its reference is not published when it is in a partially initialized state (see [ state (see [CON26-J. Do not publish partially initialized objects|CON26-J. Do not publish partially initialized objects] for more information).
h2. Noncompliant Code Example (Mutable Sub-Object)
ThisIn this noncompliant code example, declaresthe thevolatile {{FORMATformat}} field {{volatile}}. However, the field storesis used to store a reference to a mutable object, {{java.text.DateFormat}}.
{code:bgColor=#FFcccc}
final class DateHandler {
private static volatile DateFormat FORMAT format=
DateFormat.getDateInstance(DateFormat.MEDIUM);
public static Date parse(String str) throws ParseException {
return FORMATformat.parse(str);
}
}
{code}
In the presence of multiple threads, this results in subtle thread-safety issues, because
Because {{DateFormat}} is not thread-safe \[[API 06|AA. Java References#API 06]\]., For example, a thread might observe correctly formatted output for an arbitrary date when it invokes {{parse()}} with a known datethe {{parse()}} method might return a value for {{Date}} that does not 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 every invocation of the {{parse()}} method. \[[API 06|AA. Java References#API 06]\]
{code:bgColor=#ccccff}
final class DateHandler {
public static Date parse(String str) throws ParseException {
DateFormat format =return DateFormat.getDateInstance(DateFormat.MEDIUM);
return format.parse(str);
}
}
{code}
This solution does not violate [OBJ11-J. Defensively copy private mutable class members before returning their references|OBJ11-J. Defensively copy private mutable class members before returning their references], because the class no longer contains internal mutable state, but rather only a local field, {{format}}.
h2. Compliant Solution (Synchronization)
This compliant solution synchronizes statements within the {{parse()}} method, and consequentlymethod, themaking {{DateHandler}} class is thread-safe \[[API 06|AA. Java References#API 06]\]. There is no requirement for declaring the {{FORMAT}} field {{volatile}}.
{code:bgColor=#ccccff}
final class DateHandler {
private static DateFormat FORMAT format=
DateFormat.getDateInstance(DateFormat.MEDIUM);
public static Date parse(String str) throws ParseException {
synchronized (FORMATformat) {
return FORMATformat.parse(str);
}
}
}
{code}
h2. Compliant Solution ({{ThreadLocal}} Storage)
This compliant solution uses a {{ThreadLocal}} object to create storea oneseparate {{DateFormat}} instance per thread.
{code:bgColor=#ccccff}
final class DateHandler {
private static final ThreadLocal<DateFormat> dfformat = new ThreadLocal<DateFormat>() {
@Override protected DateFormat initialValue() {
return DateFormat.getDateInstance(DateFormat.MEDIUM);
}
};
// ...
}
{code}
h2. Risk Assessment
AssumingIncorrectly assuming that declaring a field {{volatile}} guarantees visibility of the members of thea referenced object can cause threads to observe stale values of the members.
|| Rule || Severity || Likelihood || Remediation Cost || Priority || Level ||
| CON11-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. References
\[[Goetz 07|AA. Java References#Goetz 07]\] Pattern #2: "one-time safe publication"
\[[Miller 09|AA. Java References#Miller 09]\] Mutable Statics
\[[API 06|AA. Java References#API 06]\] Class {{java.text.DateFormat}}
\[[JLS 05|AA. Java References#JLS 05]\]
----
[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!|CON10-J. Do not override thread-safe methods with methods that are not thread-safe] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!|11. Concurrency (CON)] [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!|CON12-J. Avoid deadlock by requesting and releasing locks in the same order]
|