public class Point{
public final int x,y;
public Point(int x,int y){
this.x = x;
this.y = y;
}
}
由于Point是不可变的,因此是线程安全的,不可变的值可以被自由的共享和发布
//线程安全委托给ConcurrentHashMap
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 = Collection.unmodifiableMap(locations);
}
public Map<String,Point> getLocations(){
return unmodifialbleMap;
}
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);
}
}