gpt4 book ai didi

java - 使用 Collections.unmodifyingMap 并以 ConcurrentHashMap/HashMap 作为参数

转载 作者:行者123 更新时间:2023-11-30 01:56:22 26 4
gpt4 key购买 nike

我从 Goetz 的书(Java Concurrency in Practice)中得到了以下代码。

书上说,将 ConcurrentMap 作为 Collections.unmodifyingMap 中的参数传递将提供位置的“实时” View (即,调用下面的 getLocations() ),这意味着 setLocation 的调用将反射(reflect)给调用者。

但是,将 HashMap 作为 Collections.unmodifyingMap 中的参数传递将给出位置的原始 View (静态 View )(即,调用下面的 getLocationsAsStatic())

谁能解释一下背后的原因吗?谢谢

@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);
}

// Alternate version of getLocations (Listing 4.8)
public Map<String, Point> getLocationsAsStatic() {
return Collections.unmodifiableMap(
new HashMap<String, Point>(locations));
}
}

@Immutable
public class Point {
public final int x, y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

最佳答案

行为的差异不是由于 map 类型不同,而是由于它们的创建方式不同。 Collections.unmodifiableMap只是包装给定的 map 。

您的ConcurrentMap<String, Point> locations是您正在修改的 map ,因此当您包装它时,使用不可修改的 map 时您仍然会看到最新的值。

但是你的HashMap使用 new HashMap<String, Point>(locations) 创建。 this constructor 的文档说:

Constructs a new HashMap with the same mappings as the specified Map.

Parameters:
    m - the map whose mappings are to be placed in this map

所以它实际上将给定映射的所有条目复制到新创建的映射中。因此这张新 map 与locations没有关系。不再 map 了。

关于java - 使用 Collections.unmodifyingMap 并以 ConcurrentHashMap/HashMap 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54374455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com