Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want better concurrency than full synchronization, there is one way I know of to do it, using a ConcurrentHashMap as the backing map. The following is a sketch only.</p> <pre><code>public final class ConcurrentHashSet&lt;E&gt; extends ForwardingSet&lt;E&gt; implements Set&lt;E&gt;, Queue&lt;E&gt; { private enum Dummy { VALUE } private final ConcurrentMap&lt;E, Dummy&gt; map; ConcurrentHashSet(ConcurrentMap&lt;E, Dummy&gt; map) { super(map.keySet()); this.map = Preconditions.checkNotNull(map); } @Override public boolean add(E element) { return map.put(element, Dummy.VALUE) == null; } @Override public boolean addAll(Collection&lt;? extends E&gt; newElements) { // just the standard implementation boolean modified = false; for (E element : newElements) { modified |= add(element); } return modified; } @Override public boolean offer(E element) { return add(element); } @Override public E remove() { E polled = poll(); if (polled == null) { throw new NoSuchElementException(); } return polled; } @Override public E poll() { for (E element : this) { // Not convinced that removing via iterator is viable (check this?) if (map.remove(element) != null) { return element; } } return null; } @Override public E element() { return iterator().next(); } @Override public E peek() { Iterator&lt;E&gt; iterator = iterator(); return iterator.hasNext() ? iterator.next() : null; } } </code></pre> <p>All is not sunshine with this approach. We have no decent way to select a head element other than using the backing map's <code>entrySet().iterator().next()</code>, the result being that the map gets more and more unbalanced as time goes on. This unbalancing is a problem both due to greater bucket collisions and greater segment contention.</p> <p>Note: this code uses <a href="http://guava-libraries.googlecode.com" rel="noreferrer">Guava</a> in a few places.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload