On page 65 and 66 of Java Concurrency in Practice Brian Goetz lists the following code:
@ThreadSafe
public class DelegatingVehicleTracker {
private final Con
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
.