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

前端 未结 3 1250
臣服心动
臣服心动 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

    I think your confusion is due to misunderstanding of Collections.unmodifiableMap. Direct mutation of the map returned by Collections.unmodifiableMap is not allowed, however, mutating the backing map is totally fine (as long as the backing map allows mutation). For example:

    Map map = new HashMap<>();
    Map unmodifiableMap = Collections.unmodifiableMap(map);
    
    map.put("key","value");
    
    for (String key : unmodifiableMap.keySet()) {
       System.out.println(key); // prints key
    }
    

    So, unmodifiableMap in the DelegatingVehicleTracker example is backed by a mutable map locations (a thread-safe one). setLocation mutates locations atomically and hence changes will be visible for threads holding references to the unmodifiableMap knowing that those thread can't mutate the unmodifiableMap. Readers don't have access to locations so mutating it will be done through DelegatingVehicleTracker only and hence the name delegation.

提交回复
热议问题