packagecom.demo.test;importjava.util.Collections;importjava.util.HashMap;importjava.util.Map;importjava.util.concurrent.ConcurrentHashMap;importjava.util.concurrent.ConcurrentMap;/***@authorQQ: 1236897
**/
//基于委托的线程安全
classPoint {public final intx, y;public Point(int x, inty) {this.x =x;this.y =y;
}/*(non-Javadoc)
* @see java.lang.Object#toString()*/@OverridepublicString toString() {//TODO Auto-generated method stub
return "x: "+x+", y: "+y;
}
}//返回locations后 修改point坐标,对返回map里的point->有影响
classDelegateTracker {private final ConcurrentMaplocations;private final MapunmodifiableMap;public DelegateTracker(Mappoints) {
locations= new ConcurrentHashMap(points);
unmodifiableMap=Collections.unmodifiableMap(locations);
}public MapgetLocations() {returnunmodifiableMap;
}publicPoint getLocation(String id) {returnlocations.get(id);
}public void setLocation(String id, int x, inty) {if (locations.replace(id, new Point(x, y)) == null) {throw new IllegalArgumentException("invalid id - " +id);
}
}
}//返回locations后 修改point坐标,对返回map里的point -> 没有影响
classDelegateTrackerFixedPoint {private final ConcurrentMaplocations;private final MapunmodifiableMap;public DelegateTrackerFixedPoint(Mappoints) {
locations= new ConcurrentHashMap(points);
unmodifiableMap=Collections.unmodifiableMap(locations);
}//不同
public MapgetLocations() {return Collections.unmodifiableMap(new HashMap(locations));
}publicPoint getLocation(String id) {returnlocations.get(id);
}public void setLocation(String id, int x, inty) {if (locations.replace(id, new Point(x, y)) == null) {throw new IllegalArgumentException("invalid id - " +id);
}
}
}public classThreadDemo1 {public static voidmain(String[] args) {//test1 - DelegateTracker
Point p1 = new Point(1,1);
Point p2= new Point(2,2);
Point p3= new Point(3,3);
Point p4= new Point(4,4);
Point p5= new Point(5,5);
Map points = new HashMap();
points.put("1", p1);
points.put("2", p2);
points.put("3", p3);
points.put("4", p4);
points.put("5", p5);
DelegateTracker delegateTracker= newDelegateTracker(points);
delegateTracker.setLocation("2", 99, 99);
Map result =delegateTracker.getLocations();
delegateTracker.setLocation("3", 33, 33);for(String key:result.keySet())
{
Point point=result.get(key);
System.out.println(point.toString());
}
System.out.println("-----------------------------------------");//test2 - DelegateTrackerFixedPoint
Point f1 = new Point(1,1);
Point f2= new Point(2,2);
Point f3= new Point(3,3);
Point f4= new Point(4,4);
Point f5= new Point(5,5);
Map points2 = new HashMap();
points2.put("1", f1);
points2.put("2", f2);
points2.put("3", f3);
points2.put("4", f4);
points2.put("5", f5);
DelegateTrackerFixedPoint delegateTrackerFixedPoint= newDelegateTrackerFixedPoint(points2);
delegateTrackerFixedPoint.setLocation("2", 99, 99);
Map result2 =delegateTrackerFixedPoint.getLocations();
delegateTrackerFixedPoint.setLocation("3", 33, 33);for(String key:result2.keySet())
{
Point point=result2.get(key);
System.out.println(point.toString());
}
}
}