java集合的同步:(还需深入)
Collections.synchronizedList(List)
List list = Collections.synchronizedList(new ArrayList()); … … Synchronized(list){ Iterator i = list.iterator();//Must be in synchronized block While(i.hasNext()) foo(i.next()); } |
Collections.synchronizedSet(Set)
Set s = Collections.synchronizedSet(new HashSet()); ... synchronized(s) { Iterator i = s.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); } |
SortedSet s = Collections.synchronizedSortedSet(new HashSortedSet()); ... synchronized(s) { Iterator i = s.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); } |
SortedSet s = Collections.synchronizedSortedSet(new HashSortedSet()); SortedSet s2 = s.headSet(foo); ... synchronized(s) { // Note: s, not s2!!! Iterator i = s2.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); } |
Collections.synchronizedMap(Map)
Map m = Collections.synchronizedMap(new HashMap()); ... Set s = m.keySet(); // Needn't be in synchronized block ... synchronized(m) { // Synchronizing on m, not s! Iterator i = s.iterator(); // Must be in synchronized block while (i.hasNext()) foo(i.next()); } |
SortedMap m = Collections.synchronizedSortedMap(new HashSortedMap()); ... Set s = m.keySet(); // Needn't be in synchronized block ... synchronized(m) { // Synchronizing on m, not s! Iterator i = s.iterator(); // Must be in synchronized block while (i.hasNext()) foo(i.next()); } |
SortedMap m = Collections.synchronizedSortedMap(new HashSortedMap()); SortedMap m2 = m.subMap(foo, bar); ... Set s2 = m2.keySet(); // Needn't be in synchronized block ... synchronized(m) { // Synchronizing on m, not m2 or s2! Iterator i = s.iterator(); // Must be in synchronized block while (i.hasNext()) foo(i.next()); } |
摘自:http://blog.youkuaiyun.com/qinjienj/article/details/7684340