Java Reference
In-Depth Information
Noncompliant Code Example (Mutable Object)
This noncompliant code example declares the
Map
instance field volatile. The instance of
the
Map
object is mutable because of its
put()
method.
final class Foo {
private volatile Map<String, String> map;
public Foo() {
map = new HashMap<String, String>();
// Load some useful values into map
}
public String get(String s) {
return map.get(s);
}
public void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
map.put(key, value);
}
}
Interleaved calls to
get()
and
put()
may result in the retrieval of internally incon-
sistent values from the
Map
object because
put()
modifies its state. Declaring the object
reference volatile is insufficient to eliminate this data race.
Noncompliant Code Example (Volatile-Read, Synchronized-Write)
This noncompliant code example attempts to use the volatile-read, synchronized-write
technique described in Java Theory and Practice [Goetz 2007]. The
map
field is declared
volatile tosynchronizeitsreadsandwrites.The
put()
methodisalsosynchronizedtoen-
sure it is executed atomically.
final class Foo {
private volatile Map<String, String> map;