On page 65 and 66 of Java Concurrency in Practice Brian Goetz lists the following code:
@ThreadSafe
public class DelegatingVehicleTracker {
private final Con
In what sense would Thread A's unmodifiableMap be "live"? I do not see how changes made by Thread B via calls to setLocation() would be reflected in Thread A's unmodifiableMap
This is because getLocations()
returns an unmodifiable wrapped map of the actual mutable map.
public DelegatingVehicleTracker(Map points) {
locations = new ConcurrentHashMap(points);
unmodifiableMap = Collections.unmodifiableMap(locations);
}
...
public Map getLocations() {
return unmodifiableMap;
}
So any changes later will be automatically reflected in the original returned map since they both eventually point to the same internal Map object.
Goetz goes on to say that getLocationsAsStatic() could be called were an "unchanging view of the fleet required"
This code
public Map getLocationsAsStatic() {
return Collections.unmodifiableMap(
new HashMap(locations));
}
is static in the sense that future changes to locations
are not reflected since it returns a new map with a copy of the all the current key-value pairs.