1 package cz.cuni.amis.utils.sets; 2 3 import java.util.Collection; 4 import java.util.Iterator; 5 import java.util.Set; 6 import java.util.concurrent.CopyOnWriteArrayList; 7 8 public class ConcurrentLinkedHashSet<K> implements Set<K>{ 9 10 private ConcurrentHashSet<K> set = new ConcurrentHashSet<K>(); 11 12 private CopyOnWriteArrayList<K> holder = new CopyOnWriteArrayList<K>(); 13 14 public ConcurrentLinkedHashSet() { 15 } 16 17 @Override 18 public boolean add(K e) { 19 if (set.contains(e)) return false; 20 synchronized(set) { 21 set.add(e); 22 holder.add(e); 23 } 24 return true; 25 } 26 27 @Override 28 public boolean addAll(Collection<? extends K> c) { 29 boolean changed = false; 30 for (K element : c) { 31 changed = add(element) || changed; 32 } 33 return changed; 34 } 35 36 @Override 37 public void clear() { 38 holder.clear(); 39 } 40 41 @Override 42 public boolean contains(Object o) { 43 return set.contains(o); 44 } 45 46 @Override 47 public boolean containsAll(Collection<?> c) { 48 for (Object o : c) { 49 if (!contains(o)) return false; 50 } 51 return true; 52 } 53 54 @Override 55 public boolean isEmpty() { 56 return holder.size() == 0; 57 } 58 59 @Override 60 public Iterator<K> iterator() { 61 return holder.iterator(); 62 } 63 64 @Override 65 public boolean remove(Object o) { 66 if (!set.contains(o)) return false; 67 synchronized(set) { 68 set.remove(o); 69 holder.remove(o); 70 } 71 return true; 72 } 73 74 @Override 75 public boolean removeAll(Collection<?> c) { 76 boolean changed = false; 77 for (Object o : c) { 78 changed = remove(o) || changed; 79 } 80 return changed; 81 } 82 83 @Override 84 public boolean retainAll(Collection<?> c) { 85 clear(); 86 for (Object element : c) { 87 add((K) element); 88 } 89 return true; 90 } 91 92 @Override 93 public int size() { 94 return holder.size(); 95 } 96 97 @Override 98 public Object[] toArray() { 99 return holder.toArray(); 100 } 101 102 @Override 103 public <T> T[] toArray(T[] a) { 104 return holder.toArray(a); 105 } 106 107 }