Java并发编程实战(四)对象的组合

xiaoxiao2021-02-28  42

4.2 实例封闭

车辆追踪示例

public class MonitorVehicleTracker { @Generated("this") private final Map<String,MutablePoint> locations; public MonitorVehicleTracker(Map<String,MutablePoint> locations) { this.locations = locations; } public synchronized Map<String, MutablePoint> getLocations(){ return deppCopy(locations); } public synchronized MutablePoint getLocation(String id){ MutablePoint loc = locations.get(id); return loc == null ? null : new MutablePoint(loc); } public synchronized void setLocations(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> deppCopy(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(m); } }

这种封装虽然MutablePoint不是线程安全类,但监视器是的,这种方式实现可以满足线程的安全,但如果多个线程访问这个监视器,不断更新数据和调用最新数据,将极大降低性能。

4.3 线程安全性委托

前面提到对于车辆监视器类的每个操作都加锁,在车辆容器增大后,会非常影响性能,对于一个线程共享变量,我们可以将线程安全类的操作数据交给Map对象,实现一个ConcurrentHashMap。

public class DelegtingVehicleTracker { private final ConcurrentMap<String, Point> locations; private final Map<String, Point> unmodifiableMap; public DelegtingVehicleTracker(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 setLocations(String id, int x , int y){ if(locations.replace(id, new Point(x,y)) == null) throw new IllegalArgumentException("invalid vehicle name::" + id); } }

转载请注明原文地址: https://www.6miu.com/read-2625629.html

最新回复(0)