1 package hudson.util; 2 3 import java.util.Collection ; 4 import java.util.Collections ; 5 import java.util.Comparator ; 6 import java.util.HashMap ; 7 import java.util.Map ; 8 import java.util.Set ; 9 import java.util.TreeMap ; 10 11 20 public abstract class CopyOnWriteMap<K,V> implements Map <K,V> { 21 protected volatile Map <K,V> core; 22 25 private volatile Map <K,V> view; 26 27 protected CopyOnWriteMap(Map <K, V> core) { 28 update(core); 29 } 30 31 protected CopyOnWriteMap() { 32 update(Collections.<K,V>emptyMap()); 33 } 34 35 private void update(Map <K, V> m) { 36 core = m; 37 view = Collections.unmodifiableMap(core); 38 } 39 40 public int size() { 41 return core.size(); 42 } 43 44 public boolean isEmpty() { 45 return core.isEmpty(); 46 } 47 48 public boolean containsKey(Object key) { 49 return core.containsKey(key); 50 } 51 52 public boolean containsValue(Object value) { 53 return core.containsValue(value); 54 } 55 56 public V get(Object key) { 57 return core.get(key); 58 } 59 60 public synchronized V put(K key, V value) { 61 Map <K,V> m = copy(); 62 V r = m.put(key,value); 63 update(m); 64 65 return r; 66 } 67 68 public synchronized V remove(Object key) { 69 Map <K,V> m = copy(); 70 V r = m.remove(key); 71 update(m); 72 73 return r; 74 } 75 76 public synchronized void putAll(Map <? extends K, ? extends V> t) { 77 Map <K,V> m = copy(); 78 m.putAll(t); 79 update(m); 80 } 81 82 protected abstract Map <K,V> copy(); 83 84 public synchronized void clear() { 85 update(Collections.<K,V>emptyMap()); 86 } 87 88 91 public Set <K> keySet() { 92 return view.keySet(); 93 } 94 95 98 public Collection <V> values() { 99 return view.values(); 100 } 101 102 105 public Set <Entry<K,V>> entrySet() { 106 return view.entrySet(); 107 } 108 109 112 public static final class Hash<K,V> extends CopyOnWriteMap<K,V> { 113 public Hash(Map <K, V> core) { 114 super(new HashMap <K,V>(core)); 115 } 116 117 public Hash() { 118 } 119 120 protected Map <K,V> copy() { 121 return new HashMap <K,V>(core); 122 } 123 } 124 125 128 public static final class Tree<K,V> extends CopyOnWriteMap<K,V> { 129 private final Comparator <K> comparator; 130 131 public Tree(Map <K,V> core, Comparator <K> comparator) { 132 this(comparator); 133 putAll(core); 134 } 135 136 public Tree(Comparator <K> comparator) { 137 this.comparator = comparator; 138 } 139 140 public Tree() { 141 this(null); 142 } 143 144 protected Map <K,V> copy() { 145 TreeMap <K, V> m = new TreeMap <K, V>(comparator); 146 m.putAll(core); 147 return m; 148 } 149 } 150 } 151 | Popular Tags |