[英]Thread safety using Delegation
在实践 Java 并发时,我遇到了以下代码。
尽管Mutablepoint
不是线程安全的, MonitorVehicleTracker
是线程安全的,因为所有保护位置 Map 的不变量都使用深拷贝。 我的疑问是,仍然可以通过另一个线程从可变点更改特定车辆的位置,因为坐标 x 和 y 是公开的,它不会产生任何并发问题吗? 那么我们怎么能说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);
}
}
@NonThreadSafe
public class MutablePoint {
public int x, y;
public MutablePoint() {
x = 0;
y = 0;
}
public MutablePoint(MutablePoint p) {
this.x = p.x;
this.y = p.y;
}
}
尽管MutablePoint
包含公共变量,所有实例MutablePoint
通过返回小号MotorVehicleTracker
在地图实例的副本。 正因为如此,如果呼叫者获得的一个实例MutablePoint
和修改x
和y
,这些都是从存储在地图中的实例不同MotorVehicleTracker
。 所以MotorVehicleTracker
是线程安全的。 MutablePoint
不是,它可用于创建竞争条件。 这些竞争条件不会涉及MotorVehicleTracker
因为此类仅存储副本并返回副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.