マルチスレッドアクション---スレッドセキュリティの委任

3181 ワード

1.スレッドのセキュリティを確保するためにレプリケーションを使用


class MonitorVehicleTracker{
	private final Map<String,MutablePoint> locations;
	
	public MonitorVehicleTracker(Map<String,MutablePoint> locations){
		this.locations = deepCopy(locations);
	}
	public synchronized Map<String,MutablePoint> getLocations(){
		//             ,     locations         
		return deepCopy(locations);
	}
	
	public synchronized MutablePoint getLocation(String id){
		MutablePoint loc = locations.get(id);
		//          ,          ,     locations     ,    
		return loc==null?null:new MutablePoint(loc);
	}
	
	public synchronized void setLocation(String id,int x,int y){
		//           location  ,         
		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);//  map           
	}
}
class MutablePoint{
	public int x,y;
	public MutablePoint(){
		x=0;y=0;
	}
	public MutablePoint(MutablePoint p){
		this.x=p.x;
		this.y=p.y;
	}
}

2.同期範囲の縮小

class MonitorVehicleTracker{
	private final Map<String,MutablePoint> locations;
	private final Map<String,MutablePoint> unmodifiableMap;
	public MonitorVehicleTracker(Map<String,MutablePoint> locations){
		this.locations = new ConcurrentHashMap<String,MutablePoint>(locations);
		this.unmodifiableMap = Collections.unmodifiableMap(locations);
	}
	public /*synchronized*/ Map<String,MutablePoint> getLocations(){
		 
		return this.unmodifiableMap;
	}
	
	public /*synchronized*/ MutablePoint getLocation(String id){
		return locations.get(id);
	}
	
	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.set(x, 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);//  map           
	}
}
class MutablePoint{
	public int x,y;
	public MutablePoint(){
		x=0;y=0;
	}
	public MutablePoint(MutablePoint p){
		this.x=p.x;
		this.y=p.y;
	}
	public synchronized void set(int x,int y){
		this.x=x;
		this.y=y;
	}
}