1 11 12 package org.jivesoftware.util; 13 14 import java.util.*; 15 import java.util.concurrent.ConcurrentHashMap ; 16 17 22 public class ConcurrentHashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable , 23 java.io.Serializable 24 { 25 26 private transient ConcurrentHashMap <E,Object > map; 27 28 private static final Object PRESENT = new Object (); 30 31 35 public ConcurrentHashSet() { 36 map = new ConcurrentHashMap <E,Object >(); 37 } 38 39 48 public ConcurrentHashSet(Collection<? extends E> c) { 49 map = new ConcurrentHashMap <E,Object >(Math.max((int) (c.size()/.75f) + 1, 16)); 50 addAll(c); 51 } 52 53 62 public ConcurrentHashSet(int initialCapacity, float loadFactor) { 63 map = new ConcurrentHashMap <E,Object >(initialCapacity, loadFactor, 16); 64 } 65 66 75 public ConcurrentHashSet(int initialCapacity) { 76 map = new ConcurrentHashMap <E,Object >(initialCapacity); 77 } 78 79 public Iterator<E> iterator() { 80 return map.keySet().iterator(); 81 } 82 83 public int size() { 84 return map.size(); 85 } 86 87 public boolean isEmpty() { 88 return map.isEmpty(); 89 } 90 91 public boolean contains(Object o) { 92 return map.containsKey(o); 93 } 94 95 public boolean add(E o) { 96 return map.put(o, PRESENT)==null; 97 } 98 99 public boolean remove(Object o) { 100 return map.remove(o)==PRESENT; 101 } 102 103 public void clear() { 104 map.clear(); 105 } 106 107 public Object clone() { 108 try { 109 ConcurrentHashSet<E> newSet = (ConcurrentHashSet<E>)super.clone(); 110 newSet.map.putAll(map); 111 return newSet; 112 } 113 catch (CloneNotSupportedException e) { 114 throw new InternalError (); 115 } 116 } 117 118 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { 119 s.defaultWriteObject(); 120 121 s.writeInt(map.size()); 123 124 for (Iterator i=map.keySet().iterator(); i.hasNext(); ) 126 s.writeObject(i.next()); 127 } 128 129 133 private void readObject(java.io.ObjectInputStream s) 134 throws java.io.IOException , ClassNotFoundException 135 { 136 s.defaultReadObject(); 137 138 map = new ConcurrentHashMap <E, Object >(); 139 140 int size = s.readInt(); 142 143 for (int i=0; i<size; i++) { 145 E e = (E) s.readObject(); 146 map.put(e, PRESENT); 147 } 148 } 149 } | Popular Tags |