On page 65 and 66 of Java Concurrency in practice, Brian Goetz lists the following code:
@ThreadSafe public class DelegatingVehicleTracker { private final ConcurrentMap<String, Point> locations; private final Map<String, Point> unmodifiableMap; public DelegatingVehicleTracker(Map<String, Point> points) { locations = new ConcurrentHashMap<String, Point>(points); unmodifiableMap = Collections.unmodifiableMap(locations); } public Map<String, Point> getLocations() { return unmodifiableMap; } public Point getLocation(String id) { return locations.get(id); } public void setLocation(String id, int x, int y) { if (locations.replace(id, new Point(x, y)) == null) throw new IllegalArgumentException("invalid vehicle name: " + id); }
About this class, Goetz writes:
"... the delegating version [code above] returns an unchanged but live view of the vehicleโs location. This means that if stream A calls getLocations () and stream B subsequently changes the location of some of the points, these changes are reflected in the map returned to stream A. "
In what sense will Thread A unmodifiableMap live? I donโt see how changes made by thread B through setLocation () calls will be reflected in Thread A unmodifiableMap. It will only look like this if Thread A built a new instance of DelegatingVehicleTracker. But whether Thread A contained a reference to this class, I do not see how this is possible.
Goetz goes on to say that getLocationsAsStatic () could be called "a constant look at the required fleet." I'm confused. It seems to me that the opposite is true, that the call to getLocationsAsStatic () will really return a โliveโ view, and the call to getLocations () is a class that has not been reconstructed, would return a static unchanged view of the car park.
What am I missing here in this example?
Any thoughts or perspectives appreciated!
source share