Sometimes you will want to construct a object to be shared among multiple threads. While being initialized, the object must remain exclusive to the thread constructing it, but once initialized, it can be 'published'. that is, made visible to other threads. However, the Java Memory Model permits a compiler to modify the order of statements to that a semmingly innocuous publication turns out to permit multiple threads to have access to an object before it is fully constructed.
Noncompliant Code Example
This noncompliant code example initializes a Helper
object inside a Foo
object
Declaring an object volatile
to ensure visibility of the most up-to-date object state does not work without the use of explicit synchronization in cases where the object is not thread-safe.
Wiki Markup |
---|
In the absence of synchronization, the effect of declaring an object {{volatile}} is that multiple threads which see the new object reference never see a partially initialized object. However, this holds only when the object is "effectively immutable" \[[Goetz 07|AA. Java References#Goetz 07]\], that is, its state cannot be directly or indirectly changed after the object is initialized or published. |
Noncompliant Code Example (mutable object)
This noncompliant code example declares an instance field of type Map
as volatile
. The field can be mutated using a setter method putData()
.
Code Block | ||
---|---|---|
| ||
public class Container<K,V>Helper { volatileprivate Map<K,V>int mapn; public ContainerHelper(int n) { mapthis.n = new HashMap<K,V>(); n; } // publicother fields V get(Object k)& methods } class Foo { private Helper helper; return map.get(k); public Helper getHelper() {return helper;} public void putData(K key, V valueinitialize() { //helper Perform= validation of value map.put(key, value); } } public class Client {new Helper(42); } } |
Suppose two threads have access to the same Foo
object, and initialize()
hasn't been called yet. Then both threads will see that getHelper()
returns null
. If one thread calls initialize()
, and the other thread calls getHelper(), the second thread might receive null
. Or it might receive a fully-initialized Helper
object, with the n
field set to 42. Or it might receive a partially-initialized Helper
object where n
is not initialized; that is n
has the value 0
.
In particular, the JMM permits compilers to allocate memory for the new Helper object and assign it to the helper field, then subsequently initialize it. This provides a race window during which other threads might see a partially-initialized helper object.
Compliant Solution (volatile
)
If the helper
field is declared volatile
, then it is guaranteed to be fully constructed before becoming visible.
Code Block | ||
---|---|---|
| ||
class Foo { private volatile Helper helper; public Helper getHelper() {return helper;} public void doSomethinginitialize() { Containerhelper con = new ContainerHelper(42); } } |
Compliant Solution (final
)
If the helper
field is declared final, then it is guaranteed to be fully constructed before becoming visible.
Code Block | ||
---|---|---|
| ||
class Foo { private final Helper helper; public Helper getHelper() {return helper;} public void initialize() { helper = new Helper(42);// This needs to see the fully constructed object not just the reference if (con.map != null) { // ... } } } |
Even if the client thread sees the new reference, the object state that it observes may change in the meantime. Because the object is not effectively immutable, it is unsafe for use in a multi-threaded environment.
Compliant Solution (final)
Of course, this prevents you from subsequently setting the helper
field to a new object.
Compliant Solution (immutable
)
If the Helper
class is immutable, then it is guaranteed to be fully constructed before becoming visible. The object must be truly immutable; it is not sufficient for the program to refrain from modifying the objectThis compliant solution declares the Map
instance as final
because the semantics of final
dictate that the object will be immediately visible after initialization.
Code Block | ||
---|---|---|
| ||
public class Container<K,V>Helper { private final Map<K,V>int mapn; public ContainerHelper(int n) { mapthis.n = new HashMap<K,V>(); // Fill map with useful datan; } public// Vother get(Object k) { return map.get(k); } } |
The obvious drawback of this solution is that the setter method cannot be accommodated if the goal is to ensure immutability. The Container
and Map
class are both effectively immutable in this case because the Map
instance can only be manipulated via one of the setters whilst there is none here. The words effectively immutable are used instead of immutable because the Map
instance is technically mutable but restricted here so that it has all the immutability properties. The Map
class does not have any static
methods that can be used to change its state, so the effective immutability property is enforced.
Compliant Solution (volatile)
fields & methods, all fields are final
}
|
Note that if the Helper
object is mutable, you not only need to worry about the visibility of partially-constructed objects, but you also need to worry about the object being modified while read after it has been successfully constructed. For more information see CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members.
Compliant Solution (synchronized
)
You can also prevent a partially-constructed object from becoming visible by using locks to control access to the objectIt follows from the previous compliant solution that it is safe to declare the map
as volatile
if it is effectively immutable.
Code Block | ||
---|---|---|
| ||
public class Container<K,V>Foo { volatileprivate Map<K,V>Helper maphelper; public synchronized Helper ContainergetHelper() { map = new HashMap<K,V>(); // Fill map with useful data return helper;} public synchronized Vvoid getinitialize(Object k) { helper = returnnew map.getHelper(k42); } } |
Compliant Solution (synchronization)
Synchronizing both methods guarantees that they will never run simultaneously in different threads. If one thread calls initialize()
just before another thread calls getHelper()
, then the initialize()
block is guaranteed to finish, including the construction of the Helper
object, before getHelper()
starts. Consequently, the helper
field will only be visible after it is fully constructed.
Compliant Solution (thread-safe composition)
Some collection classes provide thread-safety over their objects. If the helper
field is contained in such a collection, then it is guaranteed to be fully constructed before becoming visible. The following code encases the helper field in a VectorThis compliant solution uses explicit synchronization to ensure thread safety. It declares the object volatile
to guard retrievals that use the getter method. A synchronized setter method is used to set the value of the Map
object.
Code Block | ||
---|---|---|
| ||
public class Container<K,V>Foo { volatileprivate Map<K,V>Vector<Helper> maphelper; public Helper ContainergetHelper() { map = new HashMap<K,V>(); return helper.elementAt(0);} public Vvoid getinitialize(Object k) { return map.get(khelper = new Vector<Helper>(); } public synchronized void putData(K key, V value) helper.add(new Helper(42)); } } |
Compliant Solution (static initialization)
In this compliant solution, the helper
field is initialized in a static block. When initialized statically, any object is guaranteed to be fully constructed before becoming visible.
Code Block | ||
---|---|---|
| ||
class Foo { private static //Helper Performhelper validation= of valuenew Helper(42); public static Helper map.put(key, value); }getHelper() {return helper;} } |
This compliant solution has the advantage that it can accommodate the setter method. Declaring the object as volatile
for safe publication using getter methods is cheaper in terms of performance, than declaring the getters as synchronized
. However, it is mandatory to synchronize the setter methodsOf course, this requires that the helper
field be static.
Risk Assessment
Failing to synchronize access to shared mutable data can cause different threads to observe different states of the object.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
CON26-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
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] \[[Bloch 01|AA. Java References#Bloch 01]\] Item 48: "Synchronize access to shared mutable data" \[[Goetz 06|AA. Java References#Goetz 06]\] Section 3.5.3 "Safe Publication Idioms" \[[Goetz 07|AA. Java References#Goetz 07]\] Pattern #2: "one-time safe publication" \[[Pugh 04|AA. Java References#Pugh 04]\] |
...
FIO36-J. Do not create multiple buffered wrappers on an InputStream 09. Input Output (FIO) 09. Input Output (FIO)