[concurrency-interest] Looking for a data struture

Peter Levart peter.levart at gmail.com
Mon Dec 22 07:15:21 EST 2014


On 12/22/2014 03:35 AM, Luke Sandberg wrote:
> Basically, I need to be able to publish a non-null object reference into a
> data structure where
> * order doesn't matter (insertion order would be nice, but i don't care
> that much)
> * add and remove identity semantics
> * concurrent iteration (weakly consistent is fine)
> * add/remove are non-blocking

If order really doesn't matter, ConcurrentHashMap is a data structure 
with plenty of uses:


public class ConcurrentIdentityHashSet<E> extends AbstractSet<E> {

     private static final class Key {
         private final Object ref;

         Key(Object ref) {
             this.ref = ref;
         }

         public int hashCode() {
             return System.identityHashCode(ref);
         }

         public boolean equals(Object obj) {
             return (obj instanceof Key) &&
                 this.ref == ((Key) obj).ref;
         }
     }

     private final ConcurrentHashMap<Key, E> map = new 
ConcurrentHashMap<>();

     public int size() {
         return map.size();
     }

     public boolean isEmpty() {
         return map.isEmpty();
     }

     public boolean contains(Object o) {
         return map.containsKey(new Key(o));
     }

     public Iterator<E> iterator() {
         return map.values().iterator();
     }

     public Object[] toArray() {
         return map.values().toArray();
     }

     public <T> T[] toArray(T[] a) {
         return map.values().toArray(a);
     }

     public boolean add(E e) {
         return map.putIfAbsent(new Key(e), e) == null;
     }

     public boolean remove(Object o) {
         return map.remove(new Key(o)) != null;
     }

     public void clear() {
         map.clear();
     }
}





Regards, Peter



More information about the Concurrency-interest mailing list