2 * (C) Copyright 2016 Pantheon Technologies, s.r.o. and others.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.opendaylight.yangtools.triemap;
18 import static com.google.common.base.Preconditions.checkNotNull;
19 import static com.google.common.base.Preconditions.checkState;
21 import com.google.common.collect.Iterators;
22 import java.io.ObjectStreamException;
23 import java.io.Serializable;
24 import java.util.AbstractMap;
25 import java.util.AbstractSet;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.NoSuchElementException;
31 import java.util.Optional;
33 import java.util.concurrent.ConcurrentMap;
34 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
37 * This is a port of Scala's TrieMap class from the Scala Collections library. This implementation does not support
38 * null keys nor null values.
40 * @author Roman Levenstein <romixlev@gmail.com>
45 @SuppressWarnings({"unchecked", "rawtypes", "unused"})
46 public final class TrieMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K,V>, Serializable {
47 private static final AtomicReferenceFieldUpdater<TrieMap, Object> ROOT_UPDATER =
48 AtomicReferenceFieldUpdater.newUpdater(TrieMap.class, Object.class, "root");
49 private static final long serialVersionUID = 1L;
54 private final EntrySet entrySet = new EntrySet();
55 private final Equivalence<? super K> equiv;
56 private final boolean readOnly;
58 private volatile Object root;
60 private TrieMap(final INode<K, V> r, final Equivalence<? super K> equiv, final boolean readOnly) {
63 this.readOnly = readOnly;
66 TrieMap(final Equivalence<? super K> equiv) {
67 this(newRootNode(), equiv, false);
71 this(Equivalence.equals());
74 /* internal methods */
76 final Equivalence<? super K> equiv() {
80 private static <K,V> INode<K, V> newRootNode() {
81 final Gen gen = new Gen();
82 return new INode<>(gen, new CNode<>(gen));
85 final boolean CAS_ROOT(final Object ov, final Object nv) {
86 checkState(!readOnly, "Attempted to modify a read-only snapshot");
87 return ROOT_UPDATER.compareAndSet (this, ov, nv);
90 // FIXME: abort = false by default
91 final INode<K, V> readRoot(final boolean abort) {
92 return RDCSS_READ_ROOT(abort);
95 final INode<K, V> readRoot() {
96 return RDCSS_READ_ROOT(false);
99 final INode<K, V> RDCSS_READ_ROOT() {
100 return RDCSS_READ_ROOT(false);
103 final INode<K, V> RDCSS_READ_ROOT(final boolean abort) {
104 final Object r = /* READ */root;
105 if (r instanceof INode) {
106 return (INode<K, V>) r;
109 checkState(r instanceof RDCSS_Descriptor, "Unhandled root %s", r);
110 return RDCSS_Complete(abort);
113 private INode<K, V> RDCSS_Complete(final boolean abort) {
115 final Object r = /* READ */root;
116 if (r instanceof INode) {
117 return (INode<K, V>) r;
120 checkState(r instanceof RDCSS_Descriptor, "Unhandled root %s", r);
121 final RDCSS_Descriptor<K, V> desc = (RDCSS_Descriptor<K, V>) r;
122 final INode<K, V> ov = desc.old;
123 final MainNode<K, V> exp = desc.expectedmain;
124 final INode<K, V> nv = desc.nv;
127 if (CAS_ROOT(desc, ov)) {
131 // Tail recursion: return RDCSS_Complete(abort);
135 final MainNode<K, V> oldmain = ov.gcasRead(this);
136 if (oldmain == exp) {
137 if (CAS_ROOT(desc, nv)) {
138 desc.committed = true;
142 // Tail recursion: return RDCSS_Complete(abort);
146 if (CAS_ROOT(desc, ov)) {
150 // Tail recursion: return RDCSS_Complete(abort);
154 private boolean RDCSS_ROOT(final INode<K, V> ov, final MainNode<K, V> expectedmain, final INode<K, V> nv) {
155 final RDCSS_Descriptor<K, V> desc = new RDCSS_Descriptor<> (ov, expectedmain, nv);
156 if (CAS_ROOT(ov, desc)) {
157 RDCSS_Complete(false);
158 return /* READ */desc.committed;
164 private void inserthc(final K k, final int hc, final V v) {
166 final INode<K, V> r = RDCSS_READ_ROOT();
167 if (r.rec_insert(k, v, hc, 0, null, this)) {
168 // Successful, we are done
172 // Tail recursion: inserthc(k, hc, v);
176 private Optional<V> insertifhc(final K k, final int hc, final V v, final Object cond) {
178 final INode<K, V> r = RDCSS_READ_ROOT();
179 final Optional<V> ret = r.rec_insertif(k, v, hc, cond, 0, null, this);
184 // Tail recursion: return insertifhc(k, hc, v, cond);
188 private Object lookuphc(final K k, final int hc) {
190 final INode<K, V> r = RDCSS_READ_ROOT();
191 final Object res = r.rec_lookup(k, hc, 0, null, this);
192 if (!INode.RESTART.equals(res)) {
196 // Tail recursion: lookuphc(k, hc)
200 private Optional<V> removehc(final K k, final V v, final int hc) {
202 final INode<K, V> r = RDCSS_READ_ROOT();
203 final Optional<V> res = r.rec_remove(k, v, hc, 0, null, this);
208 // Tail recursion: return removehc(k, v, hc);
213 * Ensure this instance is read-write, throw UnsupportedOperationException
214 * otherwise. Used by Map-type methods for quick check.
216 private void ensureReadWrite() {
218 throw new UnsupportedOperationException("Attempted to modify a read-only view");
222 boolean isReadOnly() {
229 * Returns a snapshot of this TrieMap. This operation is lock-free and
232 * The snapshot is lazily updated - the first time some branch in the
233 * snapshot or this TrieMap are accessed, they are rewritten. This means
234 * that the work of rebuilding both the snapshot and this TrieMap is
235 * distributed across all the threads doing updates or accesses subsequent
236 * to the snapshot creation.
238 public TrieMap<K, V> snapshot() {
240 final INode<K, V> r = RDCSS_READ_ROOT();
241 final MainNode<K, V> expmain = r.gcasRead(this);
242 if (RDCSS_ROOT(r, expmain, r.copyToGen(new Gen(), this))) {
243 return new TrieMap<> (r.copyToGen(new Gen(), this), equiv, readOnly);
246 // Tail recursion: return snapshot();
251 * Returns a read-only snapshot of this TrieMap. This operation is lock-free
254 * The snapshot is lazily updated - the first time some branch of this
255 * TrieMap are accessed, it is rewritten. The work of creating the snapshot
256 * is thus distributed across subsequent updates and accesses on this
257 * TrieMap by all threads. Note that the snapshot itself is never rewritten
258 * unlike when calling the `snapshot` method, but the obtained snapshot
259 * cannot be modified.
261 * This method is used by other methods such as `size` and `iterator`.
263 public TrieMap<K, V> readOnlySnapshot() {
264 // Is it a snapshot of a read-only snapshot?
270 final INode<K, V> r = RDCSS_READ_ROOT();
271 final MainNode<K, V> expmain = r.gcasRead(this);
272 if (RDCSS_ROOT(r, expmain, r.copyToGen (new Gen(), this))) {
273 return new TrieMap<>(r, equiv, true);
276 // Tail recursion: return readOnlySnapshot();
281 public void clear() {
283 final INode<K, V> r = RDCSS_READ_ROOT();
284 if (RDCSS_ROOT(r, r.gcasRead(this), newRootNode())) {
290 int computeHash(final K k) {
291 return equiv.hash(k);
294 boolean equal(final K k1, final K k2) {
295 return equiv.equivalent(k1, k2);
299 public V get(final Object key) {
300 final K k = (K) checkNotNull(key);
301 return (V) lookuphc(k, computeHash(k));
305 public V put(final K key, final V value) {
307 final K k = checkNotNull(key);
308 return insertifhc(k, computeHash(k), checkNotNull(value), null).orElse(null);
311 void add(final K key, final V value) {
312 final K k = checkNotNull(key);
313 inserthc(k, computeHash(k), checkNotNull(value));
317 public V remove(final Object key) {
319 final K k = (K) checkNotNull(key);
320 return removehc(k, (V) null, computeHash(k)).orElse(null);
324 public V putIfAbsent(final K key, final V value) {
326 final K k = checkNotNull(key);
327 return insertifhc(k, computeHash(k), checkNotNull(value), INode.KEY_ABSENT).orElse(null);
331 public boolean remove(final Object key, final Object v) {
333 final K k = (K) checkNotNull(key);
334 return removehc(k, (V) checkNotNull(v), computeHash(k)).isPresent();
338 public boolean replace(final K key, final V oldValue, final V newValue) {
340 final K k = checkNotNull(key);
341 return insertifhc(k, computeHash(k), checkNotNull(newValue), checkNotNull(oldValue)).isPresent();
345 public V replace(final K key, final V value) {
347 final K k = checkNotNull(key);
348 return insertifhc (k, computeHash(k), checkNotNull(value), INode.KEY_PRESENT).orElse(null);
352 * Return an iterator over a TrieMap.
354 * If this is a read-only snapshot, it would return a read-only iterator.
356 * If it is the original TrieMap or a non-readonly snapshot, it would return
357 * an iterator that would allow for updates.
361 Iterator<Entry<K, V>> iterator() {
362 return readOnly ? new TrieMapReadOnlyIterator<>(0, this) : new TrieMapIterator<>(0, this);
366 * Return an iterator over a TrieMap.
367 * This is a read-only iterator.
371 Iterator<Entry<K, V>> readOnlyIterator() {
372 return new TrieMapReadOnlyIterator<>(0, readOnly ? this : readOnlySnapshot());
375 private int cachedSize() {
376 INode<K, V> r = RDCSS_READ_ROOT ();
377 return r.cachedSize (this);
382 return readOnly ? cachedSize() : readOnlySnapshot().size();
386 public boolean containsKey(final Object key) {
387 return get(key) != null;
391 public Set<Entry<K, V>> entrySet() {
395 private Object writeReplace() throws ObjectStreamException {
396 return new ExternalForm(this);
399 private static final class RDCSS_Descriptor<K, V> {
401 MainNode<K, V> expectedmain;
403 volatile boolean committed = false;
405 RDCSS_Descriptor (final INode<K, V> old, final MainNode<K, V> expectedmain, final INode<K, V> nv) {
407 this.expectedmain = expectedmain;
413 * This iterator is a read-only one and does not allow for any update
414 * operations on the underlying data structure.
419 private static final class TrieMapReadOnlyIterator<K, V> extends TrieMapIterator<K, V> {
420 TrieMapReadOnlyIterator (final int level, final TrieMap<K, V> ct, final boolean mustInit) {
421 super (level, ct, mustInit);
424 TrieMapReadOnlyIterator (final int level, final TrieMap<K, V> ct) {
425 this (level, ct, true);
429 assert (ct.isReadOnly ());
434 public void remove () {
435 throw new UnsupportedOperationException ("Operation not supported for read-only iterators");
439 Entry<K, V> nextEntry(final Entry<K, V> rr) {
440 // Return non-updatable entry
445 private static class TrieMapIterator<K, V> implements Iterator<Entry<K, V>> {
447 protected TrieMap<K, V> ct;
448 private final boolean mustInit;
449 private final BasicNode[][] stack = new BasicNode[7][];
450 private final int[] stackpos = new int[7];
451 private int depth = -1;
452 private Iterator<Entry<K, V>> subiter = null;
453 private KVNode<K, V> current = null;
454 private Entry<K, V> lastReturned = null;
456 TrieMapIterator (final int level, final TrieMap<K, V> ct, final boolean mustInit) {
459 this.mustInit = mustInit;
465 TrieMapIterator (final int level, final TrieMap<K, V> ct) {
466 this (level, ct, true);
471 public boolean hasNext() {
472 return (current != null) || (subiter != null);
476 public Entry<K, V> next() {
478 throw new NoSuchElementException();
481 Entry<K, V> r = null;
482 if (subiter != null) {
486 r = current.kvPair ();
492 final Entry<K, V> rr = r;
493 return nextEntry(rr);
498 Entry<K, V> nextEntry(final Entry<K, V> rr) {
499 return new Entry<K, V>() {
500 private V updated = null;
508 public V getValue () {
509 return (updated == null) ? rr.getValue (): updated;
513 public V setValue (final V value) {
515 return ct.replace (getKey (), value);
520 private void readin (final INode<K, V> in) {
521 MainNode<K, V> m = in.gcasRead (ct);
522 if (m instanceof CNode) {
523 CNode<K, V> cn = (CNode<K, V>) m;
525 stack [depth] = cn.array;
526 stackpos [depth] = -1;
528 } else if (m instanceof TNode) {
529 current = (TNode<K, V>) m;
530 } else if (m instanceof LNode) {
531 subiter = ((LNode<K, V>) m).iterator();
533 } else if (m == null) {
539 private void checkSubiter () {
540 if (!subiter.hasNext ()) {
548 // assert (ct.isReadOnly ());
549 INode<K, V> r = ct.RDCSS_READ_ROOT ();
555 int npos = stackpos [depth] + 1;
556 if (npos < stack [depth].length) {
557 stackpos [depth] = npos;
558 BasicNode elem = stack [depth] [npos];
559 if (elem instanceof SNode) {
560 current = (SNode<K, V>) elem;
561 } else if (elem instanceof INode) {
562 readin ((INode<K, V>) elem);
573 protected TrieMapIterator<K, V> newIterator (final int _lev, final TrieMap<K, V> _ct, final boolean _mustInit) {
574 return new TrieMapIterator<> (_lev, _ct, _mustInit);
577 protected void dupTo (final TrieMapIterator<K, V> it) {
578 it.level = this.level;
580 it.depth = this.depth;
581 it.current = this.current;
583 // these need a deep copy
584 System.arraycopy (this.stack, 0, it.stack, 0, 7);
585 System.arraycopy (this.stackpos, 0, it.stackpos, 0, 7);
587 // this one needs to be evaluated
588 if (this.subiter == null) {
591 List<Entry<K, V>> lst = toList (this.subiter);
592 this.subiter = lst.iterator ();
593 it.subiter = lst.iterator ();
597 // /** Returns a sequence of iterators over subsets of this iterator.
598 // * It's used to ease the implementation of splitters for a parallel
599 // version of the TrieMap.
601 // protected def subdivide(): Seq[Iterator[(K, V)]] = if (subiter ne
603 // // the case where an LNode is being iterated
609 // } else if (depth == -1) {
614 // while (d <= depth) {
615 // val rem = stack(d).length - 1 - stackpos(d)
617 // val (arr1, arr2) = stack(d).drop(stackpos(d) + 1).splitAt(rem / 2)
620 // val it = newIterator(level + 1, ct, false)
621 // it.stack(0) = arr2
622 // it.stackpos(0) = -1
624 // it.advance() // <-- fix it
626 // return Seq(this, it)
634 private List<Entry<K, V>> toList (final Iterator<Entry<K, V>> it) {
635 ArrayList<Entry<K, V>> list = new ArrayList<> ();
636 while (it.hasNext ()) {
637 list.add (it.next());
643 System.out.println ("ctrie iterator");
644 System.out.println (Arrays.toString (stackpos));
645 System.out.println ("depth: " + depth);
646 System.out.println ("curr.: " + current);
647 // System.out.println(stack.mkString("\n"));
651 public void remove() {
652 checkState(lastReturned != null);
653 ct.remove(lastReturned.getKey());
659 * Support for EntrySet operations required by the Map interface
661 private final class EntrySet extends AbstractSet<Entry<K, V>> {
663 public Iterator<Entry<K, V>> iterator() {
664 return TrieMap.this.iterator ();
668 public final boolean contains(final Object o) {
669 if (!(o instanceof Entry)) {
673 final Entry<?, ?> e = (Entry<?, ?>) o;
674 if (e.getKey() == null) {
677 final V v = get(e.getKey());
678 return v != null && v.equals(e.getValue());
682 public final boolean remove(final Object o) {
683 if (!(o instanceof Entry)) {
686 final Entry<?, ?> e = (Entry<K, V>) o;
687 final Object key = e.getKey();
691 final Object value = e.getValue();
696 return TrieMap.this.remove(key, value);
700 public final int size () {
701 return Iterators.size(iterator());
705 public final void clear () {
706 TrieMap.this.clear ();