Java Reference
In-Depth Information
public Foo() {
map = new HashMap<String, String>();
// Load some useful values into map
}
public String get(String s) {
return map.get(s);
}
public synchronized void put(String key, String value) {
// Validate the values before inserting
if (!value.matches("[\\w]*")) {
throw new IllegalArgumentException();
}
map.put(key, value);
}
}
The volatile-read, synchronized-write technique uses synchronization to preserve
atomicityofcompoundoperations,suchasincrement,andprovidesfasteraccesstimesfor
atomic reads. However, it fails for mutable objects because the safe publication guarantee
provided by volatile extends only to the field itself (the primitive value or object refer-
ence);thereferentisexcludedfromtheguarantee,asarethereferent'smembers.Ineffect,
a write and a subsequent read of the map lack a happens-before relationship.
This technique is also discussed in The CERT ® Oracle ® Secure Coding Standard for
Java [Long2012],“VNA02-J.Ensurethatcompoundoperationsonsharedvariablesare
atomic.”
Compliant Solution (Synchronized)
This compliant solution uses method synchronization to guarantee visibility:
Click here to view code image
final class Foo {
private final Map<String, String> map;
public Foo() {
map = new HashMap<String, String>();
// Load some useful values into map
}
public synchronized String get(String s) {
return map.get(s);
}
public synchronized void put(String key, String value) {
// Validate the values before inserting
Search WWH ::




Custom Search