gpt4 book ai didi

java - 构造期间的线程安全

转载 作者:行者123 更新时间:2023-11-30 07:55:47 26 4
gpt4 key购买 nike

“Java Concurrency in Practice” 书中有一个 MonitorVehicleTracker 代码示例,它声称是线程安全的。

@ThreadSafe
public class MonitorVehicleTracker {
@GuardedBy("this") private final Map<String, MutablePoint> locations;

public MonitorVehicleTracker(Map<String, MutablePoint> locations) {
this.locations = deepCopy(locations);
}

public synchronized Map<String, MutablePoint> getLocations() {
return deepCopy(locations);
}

public synchronized MutablePoint getLocation(String id) {
MutablePoint loc = locations.get(id);
return loc == null ? null : new MutablePoint(loc);
}

public synchronized void setLocation(String id, int x, int y) {
MutablePoint loc = locations.get(id);
if (loc == null)
throw new IllegalArgumentException("No such ID: " + id);
loc.x = x;
loc.y = y;
}

private static Map<String, MutablePoint> deepCopy(Map<String, MutablePoint> m) {
Map<String, MutablePoint> result = new HashMap<String, MutablePoint>();

for (String id : m.keySet())
result.put(id, new MutablePoint(m.get(id)));

return Collections.unmodifiableMap(result);
}
}

但让我们考虑一下构造函数 locations 参数在 deepCopy() 调用期间被另一个线程修改 的情况。这可能会导致在遍历 keySet() 时抛出 ConcurrentModificationException

那么这是否意味着 MonitorVehicleTracker 不是完全线程安全的?还是thread-safety只有在对象构造完成后才会出现,调用代码负责确保MonitorVehicleTracker实例化时locations不会被修改?

最佳答案

不,该类仍然是线程安全的。

如果对象初始化失败,并不意味着它的类不再是线程安全的。它是一个线程安全的类,但未能初始化,因为它的参数被另一个线程错误地修改,破坏了它的 thread-saftey 契约。

关于java - 构造期间的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42893916/

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