How does DelegatingVehicleTracker (p. 65 Goetz) return a “live” view?

前端 未结 3 1246
臣服心动
臣服心动 2021-01-12 22:32

On page 65 and 66 of Java Concurrency in Practice Brian Goetz lists the following code:

@ThreadSafe
public class DelegatingVehicleTracker {
private final Con         


        
3条回答
  •  清酒与你
    2021-01-12 22:54

    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.

提交回复
热议问题