...
| 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> {
final Map<K,V> map;
public Container() {
map = new HashMap<K,V>();
// Fill map with useful data
}
public V get(Object k) {
return map.get(k);
}
}
|
...
It follows from the previous compliant solution that it is safe to declare the object map as volatile because if it is effectively immutable.
| Code Block | ||
|---|---|---|
| ||
public class Container<K,V> {
volatile Map<K,V> map;
public Container() {
map = new HashMap<K,V>();
// Fill map with useful data
}
public V get(Object k) {
return map.get(k);
}
}
|
...