From 36f0cdc8494d80685ccd0eeda88bf8e17aec4336 Mon Sep 17 00:00:00 2001 From: A-b Date: Sun, 5 Jan 2020 21:19:12 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E5=91=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- week_04/17/ArrayBlockingQueue | 409 +++ week_04/17/ConcurrentHashMap | 5478 ++++++++++++++++++++++++++++++ week_04/17/ConcurrentLinkedQueue | 164 + week_04/17/CopyOnWriteArrayList | 1355 ++++++++ week_04/17/DelayQueue | 281 ++ 5 files changed, 7687 insertions(+) create mode 100644 week_04/17/ArrayBlockingQueue create mode 100644 week_04/17/ConcurrentHashMap create mode 100644 week_04/17/ConcurrentLinkedQueue create mode 100644 week_04/17/CopyOnWriteArrayList create mode 100644 week_04/17/DelayQueue diff --git a/week_04/17/ArrayBlockingQueue b/week_04/17/ArrayBlockingQueue new file mode 100644 index 0000000..a383264 --- /dev/null +++ b/week_04/17/ArrayBlockingQueue @@ -0,0 +1,409 @@ +##ArrayBlockingQueue-------------阻塞队列 + 1.继承AbstractQueue; + boolean add(E e); + remove(); + element() ; + clear(); + addAll(Collection c) + + + + + 2.实现BlockingQueue,Serializable; + + 3.是线程安全的。 +##源码分析 + +##属性 + + final Object[] items;----队列数组 + int takeIndex;---获取元素的角标 + int putIndex;----放元素的角标 + int count;-----数量 + final ReentrantLock lock;--锁 + private final Condition notEmpty;--非空条件 + private final Condition notFull;----非满条件 +##构造方法 + + public ArrayBlockingQueue(int capacity) { + this(capacity, false); + } + + public ArrayBlockingQueue(int capacity, boolean fair) { + if (capacity <= 0) + throw new IllegalArgumentException(); + //初始化数组 + this.items = new Object[capacity]; + //选择锁的类型 + lock = new ReentrantLock(fair); + //两个条件 + notEmpty = lock.newCondition(); + notFull = lock.newCondition(); + } + + //初始队列,带集合进来 + public ArrayBlockingQueue(int capacity, boolean fair, + Collection c) { + this(capacity, fair); + + final ReentrantLock lock = this.lock; + lock.lock(); // Lock only for visibility, not mutual exclusion + //加锁 + try { + int i = 0; + try { + for (E e : c) { + //检查当前元素不为空 + checkNotNull(e); + items[i++] = e; + } + } catch (ArrayIndexOutOfBoundsException ex) { + throw new IllegalArgumentException(); + } + count = i; + //如果是新队列就是从头开始的,否则就是插入点的角标 + putIndex = (i == capacity) ? 0 : i; + } finally { + lock.unlock(); + } + } +##入队方法 + 1.add---调用父类的添加,但是父类只是定义了模板,具体看相关实现。 + 这里面又调用了offer方法,所以其实调用的是当前类的offer方法 + public boolean add(E e) { + return super.add(e); + } + + 2.offer + public boolean offer(E e) { + //空判定 + checkNotNull(e); + final ReentrantLock lock = this.lock; + lock.lock(); + try { + //数量和队列长度一样(队列满了) + if (count == items.length) + return false; + else { + //把这个元素放入队列中 + enqueue(e); + return true; + } + } finally { + lock.unlock(); + } + } + + //把元素放入队列 + private void enqueue(E x) { + // assert lock.getHoldCount() == 1; + // assert items[putIndex] == null; + //拿到这个时候的队列元素 + final Object[] items = this.items; + //把新元素赋值到 队列中 放置元素角标 的位置。 + items[putIndex] = x; + //如果 放置指针 已经是队列末尾了 + if (++putIndex == items.length) + //那么放置指针 就变成头部 + putIndex = 0; + //数据+1 + count++; + //唤醒队列--开始工作 + notEmpty.signal(); + } + + 3.put + + public void put(E e) throws InterruptedException { + checkNotNull(e); + final ReentrantLock lock = this.lock; + //中断异常的锁 + lock.lockInterruptibly(); + try { + //队列满了 就一直在这里等 + while (count == items.length) + notFull.await(); + //有位置了 就去添加元素 + enqueue(e); + } finally { + lock.unlock(); + } + } + 4.offer(e,long TimeUnit)----一段时间内添加元素到队列 + public boolean offer(E e, long timeout, TimeUnit unit) + throws InterruptedException { + + checkNotNull(e); + long nanos = unit.toNanos(timeout); + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + try { + //数组满了就等待nanos这么久(纳秒),如果这时间到了还是满的,就返回false + while (count == items.length) { + if (nanos <= 0) + return false; + //等待时间 + nanos = notFull.awaitNanos(nanos); + } + //有空位置,放入队列 + enqueue(e); + return true; + } finally { + lock.unlock(); + } + } +##入队方法的区别 + 1.add-----队列满了 抛异常(super里面报出来的) + 2.offer----队列满了,返回 + 3.put-----队列满了,notFull一直等,入数成功为止(中断除外) + 4.offer(e,long,TimeUnit)-----队列满了,就等待自定义的时间,还没有位置,返回。 + 5.操作依据--是根据放数据的指针 循环来放置数据 + + + + +##出队方法 + + 1.remove() + + public boolean remove(Object o) { + if (o == null) return false; + final Object[] items = this.items; + final ReentrantLock lock = this.lock; + lock.lock(); + + try { + //队列里面有数据 + if (count > 0) { + //拿到这个元素的放置角标 + final int putIndex = this.putIndex; + //获取--获取角标 + int i = takeIndex; + do { + //找到了,移除 + if (o.equals(items[i])) { + removeAt(i); + return true; + } + //如果已经到末尾了还没找到,就从头开始找前半部分 + if (++i == items.length) + i = 0; + } while (i != putIndex); + } + return false; + + + } finally { + lock.unlock(); + } + } + //真正移除的方法 + + void removeAt(final int removeIndex) { + // assert lock.getHoldCount() == 1; + // assert items[removeIndex] != null; + // assert removeIndex >= 0 && removeIndex < items.length; + + //获取当前队列 + final Object[] items = this.items; + if (removeIndex == takeIndex) { + //如果移除的角标是获取角标(就类似刚好确定了这个点, 那么后面就需要去找,该点的前,后部分) + + // removing front item; just advance + items[takeIndex] = null; + if (++takeIndex == items.length) + takeIndex = 0; + count--; + //有状态 + if (itrs != null) + //删除 + itrs.elementDequeued(); + } else { + // an "interior" remove + + // slide over all others up through putIndex. + //拿到放置角标 + final int putIndex = this.putIndex; + for (int i = removeIndex;;) { + int next = i + 1; + //从删除角标后一个点 开始找,前后都找 + + if (next == items.length) + next = 0; + //下一个角标 不是放置角标的话 + if (next != putIndex) { + //把后一个节点放到现在这个点上 + items[i] = items[next]; + //角标也替换一下 + i = next; + } else { + //如果是放置的角标,就删除当前这个节点 + items[i] = null; + this.putIndex = i; + break; + } + } + //数量减1 + count--; + //迭代器还不为空的话,继续删除 + if (itrs != null) + itrs.removedAt(removeIndex); + } + notFull.signal(); + } + + 2.poll() + + public E poll() { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + //没有了报空,还有就出队 + return (count == 0) ? null : dequeue(); + } finally { + lock.unlock(); + } + } + + ------------------dequeue()---------- + //出列 + private E dequeue() { + // assert lock.getHoldCount() == 1; + // assert items[takeIndex] != null; + //当前队列 + final Object[] items = this.items; + @SuppressWarnings("unchecked") + //获取--获取元素角标 + E x = (E) items[takeIndex]; + //把这个位置设为空 + items[takeIndex] = null; + //如果刚好到末尾了, 下一次获取的就是从头开始 + if (++takeIndex == items.length) + takeIndex = 0; + //数量少1个 + count--; + //迭代器不是空的 就清空 + if (itrs != null) + itrs.elementDequeued(); + //唤醒 + notFull.signal(); + //返回 获取角标上的元素 + return x; + } + + //等待出列,如果没有就等,一段时间还没有 就不操作了 + public E poll(long timeout, TimeUnit unit) throws InterruptedException { + long nanos = unit.toNanos(timeout); + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + try { + while (count == 0) { + if (nanos <= 0) + return null; + nanos = notEmpty.awaitNanos(nanos); + } + return dequeue(); + } finally { + lock.unlock(); + } + } + + + + + + + + 3.take(); + public E take() throws InterruptedException { + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + try { + //没有数据 就等着 + while (count == 0) + notEmpty.await(); + //出列 + return dequeue(); + } finally { + lock.unlock(); + } + } + + ##出队总结 + 1.remove()--如果没有队列抛出异常 + 2.poll()---如果没有队列返回null + 3.poll(long ,TimeUnit)--如果没有就等待long时长,还是没有返回null + 4.take();----如果没有就一直等着,等到有数据就出列。 + + ##其他方法 + 1.peek()-----获取队列头元素 + takeIndex这个时候为0 + public E peek() { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + return itemAt(takeIndex); // null when queue is empty + } finally { + lock.unlock(); + } + } + 2.remainingCapacity()----获取队列剩余容量 + 3.drainTo(Collection c)--将队列中的数据,转移到集合中去。删除队列中的数据 + public int drainTo(Collection c) { + return drainTo(c, Integer.MAX_VALUE); + } + + //将队列中的数据,转移几个到集合中去(从头依次转移),删除队列中的数据 + public int drainTo(Collection c, int maxElements) { + checkNotNull(c); + if (c == this) + throw new IllegalArgumentException(); + if (maxElements <= 0) + return 0; + final Object[] items = this.items; + final ReentrantLock lock = this.lock; + lock.lock(); + + try { + //获取指定长度(未指定就是全部) + int n = Math.min(maxElements, count); + int take = takeIndex; + int i = 0; + + try { + //从第一个元素开始取 + //取完 把队列相应位置赋值为空 + while (i < n) { + @SuppressWarnings("unchecked") + E x = (E) items[take]; + c.add(x); + + items[take] = null; + if (++take == items.length) + take = 0; + i++; + } + return n; + } finally { + // Restore invariants even if c.add() threw + if (i > 0) { + //计算出数量 + count -= i; + takeIndex = take; + //迭代器不为空,就处理数据 + if (itrs != null) { + //已经灭有数量了,清空队列 + if (count == 0) + itrs.queueIsEmpty(); + else if (i > take) + itrs.takeIndexWrapped(); + } + for (; i > 0 && lock.hasWaiters(notFull); i--) + notFull.signal(); + } + } + } finally { + lock.unlock(); + } + } + \ No newline at end of file diff --git a/week_04/17/ConcurrentHashMap b/week_04/17/ConcurrentHashMap new file mode 100644 index 0000000..7efc1af --- /dev/null +++ b/week_04/17/ConcurrentHashMap @@ -0,0 +1,5478 @@ +##ConcurrentHashMap--多线程下用的Map + 1.有一个分段锁,主要是用这个HashMap上。 + 底层实现方式也是数组,链表,红黑树。 + +##源码分析 + + { + private static final long serialVersionUID = 7249069246763182397L; + + + /* ---------------- Constants -------------- */ + + + private static final int MAXIMUM_CAPACITY = 1 << 30; + private static final int DEFAULT_CAPACITY = 16; --默认的长度 + static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;--最大容量 + private static final int DEFAULT_CONCURRENCY_LEVEL = 16; --默认并发层级 + private static final float LOAD_FACTOR = 0.75f; --扩容因子 + static final int TREEIFY_THRESHOLD = 8; ---变树阀值 + static final int UNTREEIFY_THRESHOLD = 6; --取消阀值 + static final int MIN_TREEIFY_CAPACITY = 64; --最小树容量 + private static final int MIN_TRANSFER_STRIDE = 16; --最小移动幅度 + private static int RESIZE_STAMP_BITS = 16; + private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1; + private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS; + + + + + /* + * Encodings for Node hash fields. See above for explanation. + */ + static final int MOVED = -1; // hash for forwarding nodes + static final int TREEBIN = -2; // hash for roots of trees + static final int RESERVED = -3; // hash for transient reservations + static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash + + /** Number of CPUS, to place bounds on some sizings */ + + static final int NCPU = Runtime.getRuntime().availableProcessors(); + + /** For serialization compatibility. */ + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("segments", Segment[].class), + new ObjectStreamField("segmentMask", Integer.TYPE), + new ObjectStreamField("segmentShift", Integer.TYPE) + }; + + + + /* ---------------- Nodes -------------- */ + + static class Node implements Map.Entry { + final int hash; + final K key; + volatile V val; + volatile Node next; + + Node(int hash, K key, V val, Node next) { + this.hash = hash; + this.key = key; + this.val = val; + this.next = next; + } + + public final K getKey() { return key; } + public final V getValue() { return val; } + public final int hashCode() { return key.hashCode() ^ val.hashCode(); } + public final String toString(){ return key + "=" + val; } + public final V setValue(V value) { + throw new UnsupportedOperationException(); + } + + public final boolean equals(Object o) { + Object k, v, u; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (v = e.getValue()) != null && + (k == key || k.equals(key)) && + (v == (u = val) || v.equals(u))); + } + + /** + * Virtualized support for map.get(); overridden in subclasses. + */ + Node find(int h, Object k) { + Node e = this; + if (k != null) { + do { + K ek; + if (e.hash == h && + ((ek = e.key) == k || (ek != null && k.equals(ek)))) + return e; + } while ((e = e.next) != null); + } + return null; + } + } + + /* ---------------- Static utilities -------------- */ + + + static final int spread(int h) { + return (h ^ (h >>> 16)) & HASH_BITS; + } + + + private static final int tableSizeFor(int c) { + int n = c - 1; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; + } + + + static Class comparableClassFor(Object x) { + if (x instanceof Comparable) { + Class c; Type[] ts, as; Type t; ParameterizedType p; + if ((c = x.getClass()) == String.class) // bypass checks + return c; + if ((ts = c.getGenericInterfaces()) != null) { + for (int i = 0; i < ts.length; ++i) { + if (((t = ts[i]) instanceof ParameterizedType) && + ((p = (ParameterizedType)t).getRawType() == + Comparable.class) && + (as = p.getActualTypeArguments()) != null && + as.length == 1 && as[0] == c) // type arg is c + return c; + } + } + } + return null; + } + + + @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable + static int compareComparables(Class kc, Object k, Object x) { + return (x == null || x.getClass() != kc ? 0 : + ((Comparable)k).compareTo(x)); + } + + /* ---------------- Table element access -------------- */ + + + @SuppressWarnings("unchecked") + static final Node tabAt(Node[] tab, int i) { + return (Node)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE); + } + + static final boolean casTabAt(Node[] tab, int i, + Node c, Node v) { + return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v); + } + + static final void setTabAt(Node[] tab, int i, Node v) { + U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v); + } + + /* ---------------- Fields -------------- */ + + transient volatile Node[] table; + private transient volatile Node[] nextTable; + private transient volatile long baseCount; + private transient volatile int sizeCtl; + private transient volatile int transferIndex; + private transient volatile int cellsBusy; + private transient volatile CounterCell[] counterCells; + + // views + private transient KeySetView keySet; + private transient ValuesView values; + private transient EntrySetView entrySet; + + + +##方法 + + /* ---------------- Public operations -------------- */ + + /** + * Creates a new, empty map with the default initial table size (16). + */ + public ConcurrentHashMap() { + } + + public ConcurrentHashMap(int initialCapacity) { + if (initialCapacity < 0) + throw new IllegalArgumentException(); + int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ? + MAXIMUM_CAPACITY : + tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)); + this.sizeCtl = cap; + } + + + public ConcurrentHashMap(Map m) { + this.sizeCtl = DEFAULT_CAPACITY; + putAll(m); + } + + public ConcurrentHashMap(int initialCapacity, float loadFactor) { + this(initialCapacity, loadFactor, 1); + } + + + public ConcurrentHashMap(int initialCapacity, + float loadFactor, int concurrencyLevel) { + if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0) + throw new IllegalArgumentException(); + //至少要一个节点来装 + if (initialCapacity < concurrencyLevel) // Use at least as many bins + initialCapacity = concurrencyLevel; // as estimated threads + + long size = (long)(1.0 + (long)initialCapacity / loadFactor); + int cap = (size >= (long)MAXIMUM_CAPACITY) ? + MAXIMUM_CAPACITY : tableSizeFor((int)size); + this.sizeCtl = cap; + } + + // Original (since JDK1.2) Map methods + + public int size() { + long n = sumCount(); + return ((n < 0L) ? 0 : + (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE : + (int)n); + } + + + public boolean isEmpty() { + return sumCount() <= 0L; // ignore transient negative values + } + + //获取值 + public V get(Object key) { + Node[] tab; + Node e, p; + int n, eh; + K ek; + //计算出的散列地址 + int h = spread(key.hashCode()); + if ((tab = table) != null && (n = tab.length) > 0 && + //获取这个地址上的节点 不会空(调用的UNsafe中的getObjectVolatile) + (e = tabAt(tab, (n - 1) & h)) != null) { + //地址一样 + if ((eh = e.hash) == h) { + //请求的key和内存中取出的值key一样 + //存在一个节点,并且是一样的就返回值 + if ((ek = e.key) == key || (ek != null && key.equals(ek))) + return e.val; + } + else if (eh < 0) + //用散列出的地址去找(会在整个节点上找),有就有,没有就没有 + return (p = e.find(h, key)) != null ? p.val : null; + //轮着去找 + while ((e = e.next) != null) { + if (e.hash == h && + ((ek = e.key) == key || (ek != null && key.equals(ek)))) + return e.val; + } + } + return null; + } + + + public boolean containsKey(Object key) { + return get(key) != null; + } + + public boolean containsValue(Object value) { + if (value == null) + throw new NullPointerException(); + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + V v; + if ((v = p.val) == value || (v != null && value.equals(v))) + return true; + } + } + return false; + } + + + public V put(K key, V value) { + return putVal(key, value, false); + } + + /** Implementation for put and putIfAbsent */ + final V putVal(K key, V value, boolean onlyIfAbsent) { + + if (key == null || value == null) throw new NullPointerException(); + //hash地址 + int hash = spread(key.hashCode()); + int binCount = 0; + + for (Node[] tab = table;;) { + Node f; + int n, i, fh; + //空表就初始化一个 + if (tab == null || (n = tab.length) == 0) + //初始化一个表(稍后了解) + tab = initTable(); + + //初始一个表的代码 + final Node[] initTable(){ + Node[] tab; + int sc; + //如果是空的就一直循环 + while ((tab = table) == null || tab.length == 0) { + //sizeCtl<0 表示正在初始化,或者扩容中 + if ((sc = sizeCtl) < 0) + //线程礼让(不一定会让给别人) + Thread.yield(); // lost initialization race; just spin + else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { + //把底层改成功才进行操作 + try { + //空的 + if ((tab = table) == null || tab.length == 0) { + //默认16大 + int n = (sc > 0) ? sc : DEFAULT_CAPACITY; + @SuppressWarnings("unchecked") + Node[] nt = (Node[])new Node[n]; + table = tab = nt; + sc = n - (n >>> 2); + } + } finally { + sizeCtl = sc; + } + break; + } + } + return tab; + } + //初始化代码完 + + else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { + //如果有原始数组,就获取当前节点所有的桶,是空的话,就放进去 + //调用Unsafe中的方法,更改该地址上的值 + if (casTabAt(tab, i, null, + new Node(hash, key, value, null))) + break; // no lock when adding to empty bin + } + + else if ((fh = f.hash) == MOVED) + //如果有值,但是是Moved--就迁移元素 + tab = helpTransfer(tab, f); + + -------------------------迁移的代码--------------- + final Node[] helpTransfer(Node[] tab, Node f) { + Node[] nextTab; + int sc; + + if (tab != null && (f instanceof ForwardingNode) && + //如果f是顶部节点 + //并且下一个桶节点不为空。 + (nextTab = ((ForwardingNode)f).nextTable) != null) { + + + //移动标记位 + int rs = resizeStamp(tab.length); + while (nextTab == nextTable && table == tab && + (sc = sizeCtl) < 0) { + if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || + sc == rs + MAX_RESIZERS || transferIndex <= 0) + break; + if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { + transfer(tab, nextTab); + break; + } + } + return nextTab; + } + return table; + } + + -------------------------------结束----------------------------------- + //如果头节点不是被移除,是一个正常使用的表 + else { + V oldVal = null; + //开启同步,一个一个的来,只是同步了当前的那个桶f + synchronized (f) { + //该位置无变化 + if (tabAt(tab, i) == f) { + //hash大于等于0(没有迁移,也不是树) + if (fh >= 0) { + //是链表 + binCount = 1; + //遍历整个桶 + for (Node e = f;; ++binCount) { + K ek; + if (e.hash == hash && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + //存在这个值,赋新值 + oldVal = e.val; + + (上面传递的参数onlyIfAbsent是false) + if (!onlyIfAbsent) + e.val = value; + break; + } + + //如果桶没有这个数据 + Node pred = e; + //找到桶最后那个节点,然后把新的节点添加到后面 + if ((e = e.next) == null) { + pred.next = new Node(hash, key, + value, null); + break; + } + } + } + else if (f instanceof TreeBin) { + //如果是树的节点,并且添加值成功了 + Node p; + binCount = 2; + if ((p = ((TreeBin)f).putTreeVal(hash, key, + value)) != null) { + -------------------putTreeVal方法逻辑----------------- + 1.如果根节点为空,新来的值就是根节点 + 2.否则判定根节点和新来值的hash,标记新值应该位于根节点的左边还是右边。 + 3.如果hash碰撞了,如果值和key是一样的,就返回以前的数据 + 4.如果不一样就树的左边和右边都找,知道找到为止。 + 二,维护链表的关系 + 1.如果根节点左右都是空的,会维护一个新的树出来。 + 2.同时维护一个链表前后节点。 + + -------------------------完------------------------------- + oldVal = p.val; + //修改为为新值 + if (!onlyIfAbsent) + p.val = value; + } + } + } + } + //成功插入或者修改 + if (binCount != 0) { + //达到了变成树的阀值,则尝试变树 + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); + //成功了返回旧值 + if (oldVal != null) + return oldVal; + break; + } + } + } + //添加一个元素(根据这个来看是否扩容) + addCount(1L, binCount); + return null; + } + + + public void putAll(Map m) { + tryPresize(m.size()); + for (Map.Entry e : m.entrySet()) + putVal(e.getKey(), e.getValue(), false); + } + + public V remove(Object key) { + return replaceNode(key, null, null); + } + + + final V replaceNode(Object key, V value, Object cv) { + //内存地址 + int hash = spread(key.hashCode()); + for (Node[] tab = table;;) { + Node f; + int n, i, fh; + if (tab == null || (n = tab.length) == 0 || + (f = tabAt(tab, i = (n - 1) & hash)) == null) + //表为空,或者没有这个值 跳出 + + break; + else if ((fh = f.hash) == MOVED) + //是moved 就加入迁移表 + tab = helpTransfer(tab, f); + else { + V oldVal = null; + boolean validated = false; + //同步 + synchronized (f) { + //f这个桶 有没有改过 + if (tabAt(tab, i) == f) { + //链表节点 + if (fh >= 0) { + validated = true; + //循环 寻找数据 + for (Node e = f, pred = null;;) { + K ek; + if (e.hash == hash && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + + V ev = e.val; + if (cv == null || cv == ev || + (ev != null && cv.equals(ev))) { + oldVal = ev; + //把新的值丢上去 + if (value != null) + e.val = value; + else if (pred != null) + //前面节点不为空,删除当前节点(当前节点被当前的下一个节点代替了) + pred.next = e.next; + else + //如果前置节点是空的,那就是头节点 + //unsafe直接把内存上的值改成当前节点的下一个节点 + setTabAt(tab, i, e.next); + } + break; + } + pred = e; + //始终没有,跳出。 + if ((e = e.next) == null) + break; + } + } + else if (f instanceof TreeBin) { + //如果是树节点 + + validated = true; + TreeBin t = (TreeBin)f; + TreeNode r, p; + if ((r = t.root) != null && + (p = r.findTreeNode(hash, key, null)) != null) { + //找到了节点 + + V pv = p.val; + if (cv == null || cv == pv || + (pv != null && cv.equals(pv))) { + oldVal = pv; + //把新的值换上 + if (value != null) + p.val = value; + else if (t.removeTreeNode(p)) + ------------t.removeTreeNode(p)------------- + 1.节点少的时候 将树退成链表 + -------------------------------------------- + //没有值的话 就直接删除 + setTabAt(tab, i, untreeify(t.first)); + } + } + } + } + } + //被修改过 + if (validated) { + if (oldVal != null) { + + if (value == null) + //新值为空,减少元素 + addCount(-1L, -1); + return oldVal; + } + break; + } + } + } + return null; + } + + /** + * Removes all of the mappings from this map. + */ + public void clear() { + long delta = 0L; // negative number of deletions + int i = 0; + Node[] tab = table; + //一直要循环完 + while (tab != null && i < tab.length) { + int fh; + Node f = tabAt(tab, i); + if (f == null) + ++i; + else if ((fh = f.hash) == MOVED) { + //帮助迁移 + tab = helpTransfer(tab, f); + i = 0; // restart + } + else { + synchronized (f) { + + if (tabAt(tab, i) == f) { + //f没有被改动过 + Node p = (fh >= 0 ? f : + (f instanceof TreeBin) ? + ((TreeBin)f).first : null); + //删掉每一个节点 + while (p != null) { + --delta; + p = p.next; + } + //内存地给空 + setTabAt(tab, i++, null); + } + } + } + } + //再清空一下元素 + if (delta != 0L) + addCount(delta, -1); + } + + + public KeySetView keySet() { + KeySetView ks; + return (ks = keySet) != null ? ks : (keySet = new KeySetView(this, null)); + } + + + public Collection values() { + ValuesView vs; + return (vs = values) != null ? vs : (values = new ValuesView(this)); + } + + public Set> entrySet() { + EntrySetView es; + return (es = entrySet) != null ? es : (entrySet = new EntrySetView(this)); + } + + + public int hashCode() { + int h = 0; + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) + h += p.key.hashCode() ^ p.val.hashCode(); + } + return h; + } + + + public String toString() { + Node[] t; + int f = (t = table) == null ? 0 : t.length; + Traverser it = new Traverser(t, f, 0, f); + StringBuilder sb = new StringBuilder(); + sb.append('{'); + Node p; + if ((p = it.advance()) != null) { + for (;;) { + K k = p.key; + V v = p.val; + sb.append(k == this ? "(this Map)" : k); + sb.append('='); + sb.append(v == this ? "(this Map)" : v); + if ((p = it.advance()) == null) + break; + sb.append(',').append(' '); + } + } + return sb.append('}').toString(); + } + + + public boolean equals(Object o) { + if (o != this) { + if (!(o instanceof Map)) + return false; + Map m = (Map) o; + Node[] t; + int f = (t = table) == null ? 0 : t.length; + Traverser it = new Traverser(t, f, 0, f); + for (Node p; (p = it.advance()) != null; ) { + V val = p.val; + Object v = m.get(p.key); + if (v == null || (v != val && !v.equals(val))) + return false; + } + for (Map.Entry e : m.entrySet()) { + Object mk, mv, v; + if ((mk = e.getKey()) == null || + (mv = e.getValue()) == null || + (v = get(mk)) == null || + (mv != v && !mv.equals(v))) + return false; + } + } + return true; + } + + + static class Segment extends ReentrantLock implements Serializable { + private static final long serialVersionUID = 2249069246763182397L; + final float loadFactor; + Segment(float lf) { this.loadFactor = lf; } + } + + private void writeObject(java.io.ObjectOutputStream s) + throws java.io.IOException { + // For serialization compatibility + // Emulate segment calculation from previous version of this class + int sshift = 0; + int ssize = 1; + while (ssize < DEFAULT_CONCURRENCY_LEVEL) { + ++sshift; + ssize <<= 1; + } + int segmentShift = 32 - sshift; + int segmentMask = ssize - 1; + @SuppressWarnings("unchecked") + Segment[] segments = (Segment[]) + new Segment[DEFAULT_CONCURRENCY_LEVEL]; + for (int i = 0; i < segments.length; ++i) + segments[i] = new Segment(LOAD_FACTOR); + s.putFields().put("segments", segments); + s.putFields().put("segmentShift", segmentShift); + s.putFields().put("segmentMask", segmentMask); + s.writeFields(); + + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + s.writeObject(p.key); + s.writeObject(p.val); + } + } + s.writeObject(null); + s.writeObject(null); + segments = null; // throw away + } + + + private void readObject(java.io.ObjectInputStream s) + throws java.io.IOException, ClassNotFoundException { + /* + * To improve performance in typical cases, we create nodes + * while reading, then place in table once size is known. + * However, we must also validate uniqueness and deal with + * overpopulated bins while doing so, which requires + * specialized versions of putVal mechanics. + */ + sizeCtl = -1; // force exclusion for table construction + s.defaultReadObject(); + long size = 0L; + Node p = null; + for (;;) { + @SuppressWarnings("unchecked") + K k = (K) s.readObject(); + @SuppressWarnings("unchecked") + V v = (V) s.readObject(); + if (k != null && v != null) { + p = new Node(spread(k.hashCode()), k, v, p); + ++size; + } + else + break; + } + if (size == 0L) + sizeCtl = 0; + else { + int n; + if (size >= (long)(MAXIMUM_CAPACITY >>> 1)) + n = MAXIMUM_CAPACITY; + else { + int sz = (int)size; + n = tableSizeFor(sz + (sz >>> 1) + 1); + } + @SuppressWarnings("unchecked") + Node[] tab = (Node[])new Node[n]; + int mask = n - 1; + long added = 0L; + while (p != null) { + boolean insertAtFront; + Node next = p.next, first; + int h = p.hash, j = h & mask; + if ((first = tabAt(tab, j)) == null) + insertAtFront = true; + else { + K k = p.key; + if (first.hash < 0) { + TreeBin t = (TreeBin)first; + if (t.putTreeVal(h, k, p.val) == null) + ++added; + insertAtFront = false; + } + else { + int binCount = 0; + insertAtFront = true; + Node q; K qk; + for (q = first; q != null; q = q.next) { + if (q.hash == h && + ((qk = q.key) == k || + (qk != null && k.equals(qk)))) { + insertAtFront = false; + break; + } + ++binCount; + } + if (insertAtFront && binCount >= TREEIFY_THRESHOLD) { + insertAtFront = false; + ++added; + p.next = first; + TreeNode hd = null, tl = null; + for (q = p; q != null; q = q.next) { + TreeNode t = new TreeNode + (q.hash, q.key, q.val, null, null); + if ((t.prev = tl) == null) + hd = t; + else + tl.next = t; + tl = t; + } + setTabAt(tab, j, new TreeBin(hd)); + } + } + } + if (insertAtFront) { + ++added; + p.next = first; + setTabAt(tab, j, p); + } + p = next; + } + table = tab; + sizeCtl = n - (n >>> 2); + baseCount = added; + } + } + + // ConcurrentMap methods + + + public V putIfAbsent(K key, V value) { + return putVal(key, value, true); + } + + + public boolean remove(Object key, Object value) { + if (key == null) + throw new NullPointerException(); + return value != null && replaceNode(key, null, value) != null; + } + + + public boolean replace(K key, V oldValue, V newValue) { + if (key == null || oldValue == null || newValue == null) + throw new NullPointerException(); + return replaceNode(key, newValue, oldValue) != null; + } + + + public V replace(K key, V value) { + if (key == null || value == null) + throw new NullPointerException(); + return replaceNode(key, value, null); + } + + // Overrides of JDK8+ Map extension method defaults + + + public V getOrDefault(Object key, V defaultValue) { + V v; + return (v = get(key)) == null ? defaultValue : v; + } + + public void forEach(BiConsumer action) { + if (action == null) throw new NullPointerException(); + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + action.accept(p.key, p.val); + } + } + } + + public void replaceAll(BiFunction function) { + if (function == null) throw new NullPointerException(); + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + V oldValue = p.val; + for (K key = p.key;;) { + V newValue = function.apply(key, oldValue); + if (newValue == null) + throw new NullPointerException(); + if (replaceNode(key, newValue, oldValue) != null || + (oldValue = get(key)) == null) + break; + } + } + } + } + + + public V computeIfAbsent(K key, Function mappingFunction) { + if (key == null || mappingFunction == null) + throw new NullPointerException(); + int h = spread(key.hashCode()); + V val = null; + int binCount = 0; + for (Node[] tab = table;;) { + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) + tab = initTable(); + else if ((f = tabAt(tab, i = (n - 1) & h)) == null) { + Node r = new ReservationNode(); + synchronized (r) { + if (casTabAt(tab, i, null, r)) { + binCount = 1; + Node node = null; + try { + if ((val = mappingFunction.apply(key)) != null) + node = new Node(h, key, val, null); + } finally { + setTabAt(tab, i, node); + } + } + } + if (binCount != 0) + break; + } + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); + else { + boolean added = false; + synchronized (f) { + if (tabAt(tab, i) == f) { + if (fh >= 0) { + binCount = 1; + for (Node e = f;; ++binCount) { + K ek; V ev; + if (e.hash == h && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + val = e.val; + break; + } + Node pred = e; + if ((e = e.next) == null) { + if ((val = mappingFunction.apply(key)) != null) { + added = true; + pred.next = new Node(h, key, val, null); + } + break; + } + } + } + else if (f instanceof TreeBin) { + binCount = 2; + TreeBin t = (TreeBin)f; + TreeNode r, p; + if ((r = t.root) != null && + (p = r.findTreeNode(h, key, null)) != null) + val = p.val; + else if ((val = mappingFunction.apply(key)) != null) { + added = true; + t.putTreeVal(h, key, val); + } + } + } + } + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); + if (!added) + return val; + break; + } + } + } + if (val != null) + addCount(1L, binCount); + return val; + } + + public V computeIfPresent(K key, BiFunction remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + int h = spread(key.hashCode()); + V val = null; + int delta = 0; + int binCount = 0; + for (Node[] tab = table;;) { + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) + tab = initTable(); + else if ((f = tabAt(tab, i = (n - 1) & h)) == null) + break; + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); + else { + synchronized (f) { + if (tabAt(tab, i) == f) { + if (fh >= 0) { + binCount = 1; + for (Node e = f, pred = null;; ++binCount) { + K ek; + if (e.hash == h && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + val = remappingFunction.apply(key, e.val); + if (val != null) + e.val = val; + else { + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + break; + } + pred = e; + if ((e = e.next) == null) + break; + } + } + else if (f instanceof TreeBin) { + binCount = 2; + TreeBin t = (TreeBin)f; + TreeNode r, p; + if ((r = t.root) != null && + (p = r.findTreeNode(h, key, null)) != null) { + val = remappingFunction.apply(key, p.val); + if (val != null) + p.val = val; + else { + delta = -1; + if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); + } + } + } + } + } + if (binCount != 0) + break; + } + } + if (delta != 0) + addCount((long)delta, binCount); + return val; + } + + + public V compute(K key, + BiFunction remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + int h = spread(key.hashCode()); + V val = null; + int delta = 0; + int binCount = 0; + for (Node[] tab = table;;) { + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) + tab = initTable(); + else if ((f = tabAt(tab, i = (n - 1) & h)) == null) { + Node r = new ReservationNode(); + synchronized (r) { + if (casTabAt(tab, i, null, r)) { + binCount = 1; + Node node = null; + try { + if ((val = remappingFunction.apply(key, null)) != null) { + delta = 1; + node = new Node(h, key, val, null); + } + } finally { + setTabAt(tab, i, node); + } + } + } + if (binCount != 0) + break; + } + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); + else { + synchronized (f) { + if (tabAt(tab, i) == f) { + if (fh >= 0) { + binCount = 1; + for (Node e = f, pred = null;; ++binCount) { + K ek; + if (e.hash == h && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + val = remappingFunction.apply(key, e.val); + if (val != null) + e.val = val; + else { + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + break; + } + pred = e; + if ((e = e.next) == null) { + val = remappingFunction.apply(key, null); + if (val != null) { + delta = 1; + pred.next = + new Node(h, key, val, null); + } + break; + } + } + } + else if (f instanceof TreeBin) { + binCount = 1; + TreeBin t = (TreeBin)f; + TreeNode r, p; + if ((r = t.root) != null) + p = r.findTreeNode(h, key, null); + else + p = null; + V pv = (p == null) ? null : p.val; + val = remappingFunction.apply(key, pv); + if (val != null) { + if (p != null) + p.val = val; + else { + delta = 1; + t.putTreeVal(h, key, val); + } + } + else if (p != null) { + delta = -1; + if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); + } + } + } + } + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); + break; + } + } + } + if (delta != 0) + addCount((long)delta, binCount); + return val; + } + + /** + * If the specified key is not already associated with a + * (non-null) value, associates it with the given value. + * Otherwise, replaces the value with the results of the given + * remapping function, or removes if {@code null}. The entire + * method invocation is performed atomically. Some attempted + * update operations on this map by other threads may be blocked + * while computation is in progress, so the computation should be + * short and simple, and must not attempt to update any other + * mappings of this Map. + * + * @param key key with which the specified value is to be associated + * @param value the value to use if absent + * @param remappingFunction the function to recompute a value if present + * @return the new value associated with the specified key, or null if none + * @throws NullPointerException if the specified key or the + * remappingFunction is null + * @throws RuntimeException or Error if the remappingFunction does so, + * in which case the mapping is unchanged + */ + public V merge(K key, V value, BiFunction remappingFunction) { + if (key == null || value == null || remappingFunction == null) + throw new NullPointerException(); + int h = spread(key.hashCode()); + V val = null; + int delta = 0; + int binCount = 0; + for (Node[] tab = table;;) { + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) + tab = initTable(); + else if ((f = tabAt(tab, i = (n - 1) & h)) == null) { + if (casTabAt(tab, i, null, new Node(h, key, value, null))) { + delta = 1; + val = value; + break; + } + } + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); + else { + synchronized (f) { + if (tabAt(tab, i) == f) { + if (fh >= 0) { + binCount = 1; + for (Node e = f, pred = null;; ++binCount) { + K ek; + if (e.hash == h && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + val = remappingFunction.apply(e.val, value); + if (val != null) + e.val = val; + else { + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + break; + } + pred = e; + if ((e = e.next) == null) { + delta = 1; + val = value; + pred.next = + new Node(h, key, val, null); + break; + } + } + } + else if (f instanceof TreeBin) { + binCount = 2; + TreeBin t = (TreeBin)f; + TreeNode r = t.root; + TreeNode p = (r == null) ? null : + r.findTreeNode(h, key, null); + val = (p == null) ? value : + remappingFunction.apply(p.val, value); + if (val != null) { + if (p != null) + p.val = val; + else { + delta = 1; + t.putTreeVal(h, key, val); + } + } + else if (p != null) { + delta = -1; + if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); + } + } + } + } + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); + break; + } + } + } + if (delta != 0) + addCount((long)delta, binCount); + return val; + } + + // Hashtable legacy methods + + + public boolean contains(Object value) { + return containsValue(value); + } + + /** + * Returns an enumeration of the keys in this table. + * + * @return an enumeration of the keys in this table + * @see #keySet() + */ + public Enumeration keys() { + Node[] t; + int f = (t = table) == null ? 0 : t.length; + return new KeyIterator(t, f, 0, f, this); + } + + /** + * Returns an enumeration of the values in this table. + * + * @return an enumeration of the values in this table + * @see #values() + */ + public Enumeration elements() { + Node[] t; + int f = (t = table) == null ? 0 : t.length; + return new ValueIterator(t, f, 0, f, this); + } + + // ConcurrentHashMap-only methods + + + public long mappingCount() { + long n = sumCount(); + return (n < 0L) ? 0L : n; // ignore transient negative values + } + + + public static KeySetView newKeySet() { + return new KeySetView + (new ConcurrentHashMap(), Boolean.TRUE); + } + + + public static KeySetView newKeySet(int initialCapacity) { + return new KeySetView + (new ConcurrentHashMap(initialCapacity), Boolean.TRUE); + } + + public KeySetView keySet(V mappedValue) { + if (mappedValue == null) + throw new NullPointerException(); + return new KeySetView(this, mappedValue); + } + + /* ---------------- Special Nodes -------------- */ + + /** + * A node inserted at head of bins during transfer operations. + */ + static final class ForwardingNode extends Node { + final Node[] nextTable; + ForwardingNode(Node[] tab) { + super(MOVED, null, null, null); + this.nextTable = tab; + } + + Node find(int h, Object k) { + // loop to avoid arbitrarily deep recursion on forwarding nodes + outer: for (Node[] tab = nextTable;;) { + Node e; int n; + if (k == null || tab == null || (n = tab.length) == 0 || + (e = tabAt(tab, (n - 1) & h)) == null) + return null; + for (;;) { + int eh; K ek; + if ((eh = e.hash) == h && + ((ek = e.key) == k || (ek != null && k.equals(ek)))) + return e; + if (eh < 0) { + if (e instanceof ForwardingNode) { + tab = ((ForwardingNode)e).nextTable; + continue outer; + } + else + return e.find(h, k); + } + if ((e = e.next) == null) + return null; + } + } + } + } + + /** + * A place-holder node used in computeIfAbsent and compute + */ + static final class ReservationNode extends Node { + ReservationNode() { + super(RESERVED, null, null, null); + } + + Node find(int h, Object k) { + return null; + } + } + + /* ---------------- Table Initialization and Resizing -------------- */ + + /** + * Returns the stamp bits for resizing a table of size n. + * Must be negative when shifted left by RESIZE_STAMP_SHIFT. + */ + static final int resizeStamp(int n) { + return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1)); + } + + /** + * Initializes table, using the size recorded in sizeCtl. + */ + private final Node[] initTable() { + Node[] tab; int sc; + while ((tab = table) == null || tab.length == 0) { + if ((sc = sizeCtl) < 0) + Thread.yield(); // lost initialization race; just spin + else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { + try { + if ((tab = table) == null || tab.length == 0) { + int n = (sc > 0) ? sc : DEFAULT_CAPACITY; + @SuppressWarnings("unchecked") + Node[] nt = (Node[])new Node[n]; + table = tab = nt; + sc = n - (n >>> 2); + } + } finally { + sizeCtl = sc; + } + break; + } + } + return tab; + } + + /** + * Adds to count, and if table is too small and not already + * resizing, initiates transfer. If already resizing, helps + * perform transfer if work is available. Rechecks occupancy + * after a transfer to see if another resize is already needed + * because resizings are lagging additions. + * + * @param x the count to add + * @param check if <0, don't check resize, if <= 1 only check if uncontended + */ + private final void addCount(long x, int check) { + CounterCell[] as; long b, s; + if ((as = counterCells) != null || + !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) { + CounterCell a; long v; int m; + boolean uncontended = true; + if (as == null || (m = as.length - 1) < 0 || + (a = as[ThreadLocalRandom.getProbe() & m]) == null || + !(uncontended = + U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) { + fullAddCount(x, uncontended); + return; + } + if (check <= 1) + return; + s = sumCount(); + } + if (check >= 0) { + Node[] tab, nt; int n, sc; + while (s >= (long)(sc = sizeCtl) && (tab = table) != null && + (n = tab.length) < MAXIMUM_CAPACITY) { + int rs = resizeStamp(n); + if (sc < 0) { + if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || + sc == rs + MAX_RESIZERS || (nt = nextTable) == null || + transferIndex <= 0) + break; + if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) + transfer(tab, nt); + } + else if (U.compareAndSwapInt(this, SIZECTL, sc, + (rs << RESIZE_STAMP_SHIFT) + 2)) + transfer(tab, null); + s = sumCount(); + } + } + } + + /** + * Helps transfer if a resize is in progress. + */ + final Node[] helpTransfer(Node[] tab, Node f) { + Node[] nextTab; int sc; + if (tab != null && (f instanceof ForwardingNode) && + (nextTab = ((ForwardingNode)f).nextTable) != null) { + int rs = resizeStamp(tab.length); + while (nextTab == nextTable && table == tab && + (sc = sizeCtl) < 0) { + if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || + sc == rs + MAX_RESIZERS || transferIndex <= 0) + break; + if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { + transfer(tab, nextTab); + break; + } + } + return nextTab; + } + return table; + } + + /** + * Tries to presize table to accommodate the given number of elements. + * + * @param size number of elements (doesn't need to be perfectly accurate) + */ + private final void tryPresize(int size) { + int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : + tableSizeFor(size + (size >>> 1) + 1); + int sc; + while ((sc = sizeCtl) >= 0) { + Node[] tab = table; int n; + if (tab == null || (n = tab.length) == 0) { + n = (sc > c) ? sc : c; + if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { + try { + if (table == tab) { + @SuppressWarnings("unchecked") + Node[] nt = (Node[])new Node[n]; + table = nt; + sc = n - (n >>> 2); + } + } finally { + sizeCtl = sc; + } + } + } + else if (c <= sc || n >= MAXIMUM_CAPACITY) + break; + else if (tab == table) { + int rs = resizeStamp(n); + if (sc < 0) { + Node[] nt; + if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || + sc == rs + MAX_RESIZERS || (nt = nextTable) == null || + transferIndex <= 0) + break; + if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) + transfer(tab, nt); + } + else if (U.compareAndSwapInt(this, SIZECTL, sc, + (rs << RESIZE_STAMP_SHIFT) + 2)) + transfer(tab, null); + } + } + } + + /** + * Moves and/or copies the nodes in each bin to new table. See + * above for explanation. + */ + private final void transfer(Node[] tab, Node[] nextTab) { + int n = tab.length, stride; + if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE) + stride = MIN_TRANSFER_STRIDE; // subdivide range + if (nextTab == null) { // initiating + try { + @SuppressWarnings("unchecked") + Node[] nt = (Node[])new Node[n << 1]; + nextTab = nt; + } catch (Throwable ex) { // try to cope with OOME + sizeCtl = Integer.MAX_VALUE; + return; + } + nextTable = nextTab; + transferIndex = n; + } + int nextn = nextTab.length; + ForwardingNode fwd = new ForwardingNode(nextTab); + boolean advance = true; + boolean finishing = false; // to ensure sweep before committing nextTab + for (int i = 0, bound = 0;;) { + Node f; int fh; + while (advance) { + int nextIndex, nextBound; + if (--i >= bound || finishing) + advance = false; + else if ((nextIndex = transferIndex) <= 0) { + i = -1; + advance = false; + } + else if (U.compareAndSwapInt + (this, TRANSFERINDEX, nextIndex, + nextBound = (nextIndex > stride ? + nextIndex - stride : 0))) { + bound = nextBound; + i = nextIndex - 1; + advance = false; + } + } + if (i < 0 || i >= n || i + n >= nextn) { + int sc; + if (finishing) { + nextTable = null; + table = nextTab; + sizeCtl = (n << 1) - (n >>> 1); + return; + } + if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) { + if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) + return; + finishing = advance = true; + i = n; // recheck before commit + } + } + else if ((f = tabAt(tab, i)) == null) + advance = casTabAt(tab, i, null, fwd); + else if ((fh = f.hash) == MOVED) + advance = true; // already processed + else { + synchronized (f) { + if (tabAt(tab, i) == f) { + Node ln, hn; + if (fh >= 0) { + int runBit = fh & n; + Node lastRun = f; + for (Node p = f.next; p != null; p = p.next) { + int b = p.hash & n; + if (b != runBit) { + runBit = b; + lastRun = p; + } + } + if (runBit == 0) { + ln = lastRun; + hn = null; + } + else { + hn = lastRun; + ln = null; + } + for (Node p = f; p != lastRun; p = p.next) { + int ph = p.hash; K pk = p.key; V pv = p.val; + if ((ph & n) == 0) + ln = new Node(ph, pk, pv, ln); + else + hn = new Node(ph, pk, pv, hn); + } + setTabAt(nextTab, i, ln); + setTabAt(nextTab, i + n, hn); + setTabAt(tab, i, fwd); + advance = true; + } + else if (f instanceof TreeBin) { + TreeBin t = (TreeBin)f; + TreeNode lo = null, loTail = null; + TreeNode hi = null, hiTail = null; + int lc = 0, hc = 0; + for (Node e = t.first; e != null; e = e.next) { + int h = e.hash; + TreeNode p = new TreeNode + (h, e.key, e.val, null, null); + if ((h & n) == 0) { + if ((p.prev = loTail) == null) + lo = p; + else + loTail.next = p; + loTail = p; + ++lc; + } + else { + if ((p.prev = hiTail) == null) + hi = p; + else + hiTail.next = p; + hiTail = p; + ++hc; + } + } + ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : + (hc != 0) ? new TreeBin(lo) : t; + hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : + (lc != 0) ? new TreeBin(hi) : t; + setTabAt(nextTab, i, ln); + setTabAt(nextTab, i + n, hn); + setTabAt(tab, i, fwd); + advance = true; + } + } + } + } + } + } + + /* ---------------- Counter support -------------- */ + + /** + * A padded cell for distributing counts. Adapted from LongAdder + * and Striped64. See their internal docs for explanation. + */ + @sun.misc.Contended static final class CounterCell { + volatile long value; + CounterCell(long x) { value = x; } + } + + final long sumCount() { + CounterCell[] as = counterCells; CounterCell a; + long sum = baseCount; + if (as != null) { + for (int i = 0; i < as.length; ++i) { + if ((a = as[i]) != null) + sum += a.value; + } + } + return sum; + } + + // See LongAdder version for explanation + private final void fullAddCount(long x, boolean wasUncontended) { + int h; + if ((h = ThreadLocalRandom.getProbe()) == 0) { + ThreadLocalRandom.localInit(); // force initialization + h = ThreadLocalRandom.getProbe(); + wasUncontended = true; + } + boolean collide = false; // True if last slot nonempty + for (;;) { + CounterCell[] as; CounterCell a; int n; long v; + if ((as = counterCells) != null && (n = as.length) > 0) { + if ((a = as[(n - 1) & h]) == null) { + if (cellsBusy == 0) { // Try to attach new Cell + CounterCell r = new CounterCell(x); // Optimistic create + if (cellsBusy == 0 && + U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { + boolean created = false; + try { // Recheck under lock + CounterCell[] rs; int m, j; + if ((rs = counterCells) != null && + (m = rs.length) > 0 && + rs[j = (m - 1) & h] == null) { + rs[j] = r; + created = true; + } + } finally { + cellsBusy = 0; + } + if (created) + break; + continue; // Slot is now non-empty + } + } + collide = false; + } + else if (!wasUncontended) // CAS already known to fail + wasUncontended = true; // Continue after rehash + else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x)) + break; + else if (counterCells != as || n >= NCPU) + collide = false; // At max size or stale + else if (!collide) + collide = true; + else if (cellsBusy == 0 && + U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { + try { + if (counterCells == as) {// Expand table unless stale + CounterCell[] rs = new CounterCell[n << 1]; + for (int i = 0; i < n; ++i) + rs[i] = as[i]; + counterCells = rs; + } + } finally { + cellsBusy = 0; + } + collide = false; + continue; // Retry with expanded table + } + h = ThreadLocalRandom.advanceProbe(h); + } + else if (cellsBusy == 0 && counterCells == as && + U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { + boolean init = false; + try { // Initialize table + if (counterCells == as) { + CounterCell[] rs = new CounterCell[2]; + rs[h & 1] = new CounterCell(x); + counterCells = rs; + init = true; + } + } finally { + cellsBusy = 0; + } + if (init) + break; + } + else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x)) + break; // Fall back on using base + } + } + + /* ---------------- Conversion from/to TreeBins -------------- */ + + /** + * Replaces all linked nodes in bin at given index unless table is + * too small, in which case resizes instead. + */ + private final void treeifyBin(Node[] tab, int index) { + Node b; int n, sc; + if (tab != null) { + if ((n = tab.length) < MIN_TREEIFY_CAPACITY) + tryPresize(n << 1); + else if ((b = tabAt(tab, index)) != null && b.hash >= 0) { + synchronized (b) { + if (tabAt(tab, index) == b) { + TreeNode hd = null, tl = null; + for (Node e = b; e != null; e = e.next) { + TreeNode p = + new TreeNode(e.hash, e.key, e.val, + null, null); + if ((p.prev = tl) == null) + hd = p; + else + tl.next = p; + tl = p; + } + setTabAt(tab, index, new TreeBin(hd)); + } + } + } + } + } + + /** + * Returns a list on non-TreeNodes replacing those in given list. + */ + static Node untreeify(Node b) { + Node hd = null, tl = null; + for (Node q = b; q != null; q = q.next) { + Node p = new Node(q.hash, q.key, q.val, null); + if (tl == null) + hd = p; + else + tl.next = p; + tl = p; + } + return hd; + } + + /* ---------------- TreeNodes -------------- */ + + /** + * Nodes for use in TreeBins + */ + static final class TreeNode extends Node { + TreeNode parent; // red-black tree links + TreeNode left; + TreeNode right; + TreeNode prev; // needed to unlink next upon deletion + boolean red; + + TreeNode(int hash, K key, V val, Node next, + TreeNode parent) { + super(hash, key, val, next); + this.parent = parent; + } + + Node find(int h, Object k) { + return findTreeNode(h, k, null); + } + + /** + * Returns the TreeNode (or null if not found) for the given key + * starting at given root. + */ + final TreeNode findTreeNode(int h, Object k, Class kc) { + if (k != null) { + TreeNode p = this; + do { + int ph, dir; K pk; TreeNode q; + TreeNode pl = p.left, pr = p.right; + if ((ph = p.hash) > h) + p = pl; + else if (ph < h) + p = pr; + else if ((pk = p.key) == k || (pk != null && k.equals(pk))) + return p; + else if (pl == null) + p = pr; + else if (pr == null) + p = pl; + else if ((kc != null || + (kc = comparableClassFor(k)) != null) && + (dir = compareComparables(kc, k, pk)) != 0) + p = (dir < 0) ? pl : pr; + else if ((q = pr.findTreeNode(h, k, kc)) != null) + return q; + else + p = pl; + } while (p != null); + } + return null; + } + } + + /* ---------------- TreeBins -------------- */ + + /** + * TreeNodes used at the heads of bins. TreeBins do not hold user + * keys or values, but instead point to list of TreeNodes and + * their root. They also maintain a parasitic read-write lock + * forcing writers (who hold bin lock) to wait for readers (who do + * not) to complete before tree restructuring operations. + */ + static final class TreeBin extends Node { + TreeNode root; + volatile TreeNode first; + volatile Thread waiter; + volatile int lockState; + // values for lockState + static final int WRITER = 1; // set while holding write lock + static final int WAITER = 2; // set when waiting for write lock + static final int READER = 4; // increment value for setting read lock + + /** + * Tie-breaking utility for ordering insertions when equal + * hashCodes and non-comparable. We don't require a total + * order, just a consistent insertion rule to maintain + * equivalence across rebalancings. Tie-breaking further than + * necessary simplifies testing a bit. + */ + static int tieBreakOrder(Object a, Object b) { + int d; + if (a == null || b == null || + (d = a.getClass().getName(). + compareTo(b.getClass().getName())) == 0) + d = (System.identityHashCode(a) <= System.identityHashCode(b) ? + -1 : 1); + return d; + } + + /** + * Creates bin with initial set of nodes headed by b. + */ + TreeBin(TreeNode b) { + super(TREEBIN, null, null, null); + this.first = b; + TreeNode r = null; + for (TreeNode x = b, next; x != null; x = next) { + next = (TreeNode)x.next; + x.left = x.right = null; + if (r == null) { + x.parent = null; + x.red = false; + r = x; + } + else { + K k = x.key; + int h = x.hash; + Class kc = null; + for (TreeNode p = r;;) { + int dir, ph; + K pk = p.key; + if ((ph = p.hash) > h) + dir = -1; + else if (ph < h) + dir = 1; + else if ((kc == null && + (kc = comparableClassFor(k)) == null) || + (dir = compareComparables(kc, k, pk)) == 0) + dir = tieBreakOrder(k, pk); + TreeNode xp = p; + if ((p = (dir <= 0) ? p.left : p.right) == null) { + x.parent = xp; + if (dir <= 0) + xp.left = x; + else + xp.right = x; + r = balanceInsertion(r, x); + break; + } + } + } + } + this.root = r; + assert checkInvariants(root); + } + + /** + * Acquires write lock for tree restructuring. + */ + private final void lockRoot() { + if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER)) + contendedLock(); // offload to separate method + } + + /** + * Releases write lock for tree restructuring. + */ + private final void unlockRoot() { + lockState = 0; + } + + /** + * Possibly blocks awaiting root lock. + */ + private final void contendedLock() { + boolean waiting = false; + for (int s;;) { + if (((s = lockState) & ~WAITER) == 0) { + if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) { + if (waiting) + waiter = null; + return; + } + } + else if ((s & WAITER) == 0) { + if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) { + waiting = true; + waiter = Thread.currentThread(); + } + } + else if (waiting) + LockSupport.park(this); + } + } + + /** + * Returns matching node or null if none. Tries to search + * using tree comparisons from root, but continues linear + * search when lock not available. + */ + final Node find(int h, Object k) { + if (k != null) { + for (Node e = first; e != null; ) { + int s; K ek; + if (((s = lockState) & (WAITER|WRITER)) != 0) { + if (e.hash == h && + ((ek = e.key) == k || (ek != null && k.equals(ek)))) + return e; + e = e.next; + } + else if (U.compareAndSwapInt(this, LOCKSTATE, s, + s + READER)) { + TreeNode r, p; + try { + p = ((r = root) == null ? null : + r.findTreeNode(h, k, null)); + } finally { + Thread w; + if (U.getAndAddInt(this, LOCKSTATE, -READER) == + (READER|WAITER) && (w = waiter) != null) + LockSupport.unpark(w); + } + return p; + } + } + } + return null; + } + + /** + * Finds or adds a node. + * @return null if added + */ + final TreeNode putTreeVal(int h, K k, V v) { + Class kc = null; + boolean searched = false; + for (TreeNode p = root;;) { + int dir, ph; K pk; + if (p == null) { + first = root = new TreeNode(h, k, v, null, null); + break; + } + else if ((ph = p.hash) > h) + dir = -1; + else if (ph < h) + dir = 1; + else if ((pk = p.key) == k || (pk != null && k.equals(pk))) + return p; + else if ((kc == null && + (kc = comparableClassFor(k)) == null) || + (dir = compareComparables(kc, k, pk)) == 0) { + if (!searched) { + TreeNode q, ch; + searched = true; + if (((ch = p.left) != null && + (q = ch.findTreeNode(h, k, kc)) != null) || + ((ch = p.right) != null && + (q = ch.findTreeNode(h, k, kc)) != null)) + return q; + } + dir = tieBreakOrder(k, pk); + } + + TreeNode xp = p; + if ((p = (dir <= 0) ? p.left : p.right) == null) { + TreeNode x, f = first; + first = x = new TreeNode(h, k, v, f, xp); + if (f != null) + f.prev = x; + if (dir <= 0) + xp.left = x; + else + xp.right = x; + if (!xp.red) + x.red = true; + else { + lockRoot(); + try { + root = balanceInsertion(root, x); + } finally { + unlockRoot(); + } + } + break; + } + } + assert checkInvariants(root); + return null; + } + + /** + * Removes the given node, that must be present before this + * call. This is messier than typical red-black deletion code + * because we cannot swap the contents of an interior node + * with a leaf successor that is pinned by "next" pointers + * that are accessible independently of lock. So instead we + * swap the tree linkages. + * + * @return true if now too small, so should be untreeified + */ + final boolean removeTreeNode(TreeNode p) { + TreeNode next = (TreeNode)p.next; + TreeNode pred = p.prev; // unlink traversal pointers + TreeNode r, rl; + if (pred == null) + first = next; + else + pred.next = next; + if (next != null) + next.prev = pred; + if (first == null) { + root = null; + return true; + } + if ((r = root) == null || r.right == null || // too small + (rl = r.left) == null || rl.left == null) + return true; + lockRoot(); + try { + TreeNode replacement; + TreeNode pl = p.left; + TreeNode pr = p.right; + if (pl != null && pr != null) { + TreeNode s = pr, sl; + while ((sl = s.left) != null) // find successor + s = sl; + boolean c = s.red; s.red = p.red; p.red = c; // swap colors + TreeNode sr = s.right; + TreeNode pp = p.parent; + if (s == pr) { // p was s's direct parent + p.parent = s; + s.right = p; + } + else { + TreeNode sp = s.parent; + if ((p.parent = sp) != null) { + if (s == sp.left) + sp.left = p; + else + sp.right = p; + } + if ((s.right = pr) != null) + pr.parent = s; + } + p.left = null; + if ((p.right = sr) != null) + sr.parent = p; + if ((s.left = pl) != null) + pl.parent = s; + if ((s.parent = pp) == null) + r = s; + else if (p == pp.left) + pp.left = s; + else + pp.right = s; + if (sr != null) + replacement = sr; + else + replacement = p; + } + else if (pl != null) + replacement = pl; + else if (pr != null) + replacement = pr; + else + replacement = p; + if (replacement != p) { + TreeNode pp = replacement.parent = p.parent; + if (pp == null) + r = replacement; + else if (p == pp.left) + pp.left = replacement; + else + pp.right = replacement; + p.left = p.right = p.parent = null; + } + + root = (p.red) ? r : balanceDeletion(r, replacement); + + if (p == replacement) { // detach pointers + TreeNode pp; + if ((pp = p.parent) != null) { + if (p == pp.left) + pp.left = null; + else if (p == pp.right) + pp.right = null; + p.parent = null; + } + } + } finally { + unlockRoot(); + } + assert checkInvariants(root); + return false; + } + + /* ------------------------------------------------------------ */ + // Red-black tree methods, all adapted from CLR + + static TreeNode rotateLeft(TreeNode root, + TreeNode p) { + TreeNode r, pp, rl; + if (p != null && (r = p.right) != null) { + if ((rl = p.right = r.left) != null) + rl.parent = p; + if ((pp = r.parent = p.parent) == null) + (root = r).red = false; + else if (pp.left == p) + pp.left = r; + else + pp.right = r; + r.left = p; + p.parent = r; + } + return root; + } + + static TreeNode rotateRight(TreeNode root, + TreeNode p) { + TreeNode l, pp, lr; + if (p != null && (l = p.left) != null) { + if ((lr = p.left = l.right) != null) + lr.parent = p; + if ((pp = l.parent = p.parent) == null) + (root = l).red = false; + else if (pp.right == p) + pp.right = l; + else + pp.left = l; + l.right = p; + p.parent = l; + } + return root; + } + + static TreeNode balanceInsertion(TreeNode root, + TreeNode x) { + x.red = true; + for (TreeNode xp, xpp, xppl, xppr;;) { + if ((xp = x.parent) == null) { + x.red = false; + return x; + } + else if (!xp.red || (xpp = xp.parent) == null) + return root; + if (xp == (xppl = xpp.left)) { + if ((xppr = xpp.right) != null && xppr.red) { + xppr.red = false; + xp.red = false; + xpp.red = true; + x = xpp; + } + else { + if (x == xp.right) { + root = rotateLeft(root, x = xp); + xpp = (xp = x.parent) == null ? null : xp.parent; + } + if (xp != null) { + xp.red = false; + if (xpp != null) { + xpp.red = true; + root = rotateRight(root, xpp); + } + } + } + } + else { + if (xppl != null && xppl.red) { + xppl.red = false; + xp.red = false; + xpp.red = true; + x = xpp; + } + else { + if (x == xp.left) { + root = rotateRight(root, x = xp); + xpp = (xp = x.parent) == null ? null : xp.parent; + } + if (xp != null) { + xp.red = false; + if (xpp != null) { + xpp.red = true; + root = rotateLeft(root, xpp); + } + } + } + } + } + } + + static TreeNode balanceDeletion(TreeNode root, + TreeNode x) { + for (TreeNode xp, xpl, xpr;;) { + if (x == null || x == root) + return root; + else if ((xp = x.parent) == null) { + x.red = false; + return x; + } + else if (x.red) { + x.red = false; + return root; + } + else if ((xpl = xp.left) == x) { + if ((xpr = xp.right) != null && xpr.red) { + xpr.red = false; + xp.red = true; + root = rotateLeft(root, xp); + xpr = (xp = x.parent) == null ? null : xp.right; + } + if (xpr == null) + x = xp; + else { + TreeNode sl = xpr.left, sr = xpr.right; + if ((sr == null || !sr.red) && + (sl == null || !sl.red)) { + xpr.red = true; + x = xp; + } + else { + if (sr == null || !sr.red) { + if (sl != null) + sl.red = false; + xpr.red = true; + root = rotateRight(root, xpr); + xpr = (xp = x.parent) == null ? + null : xp.right; + } + if (xpr != null) { + xpr.red = (xp == null) ? false : xp.red; + if ((sr = xpr.right) != null) + sr.red = false; + } + if (xp != null) { + xp.red = false; + root = rotateLeft(root, xp); + } + x = root; + } + } + } + else { // symmetric + if (xpl != null && xpl.red) { + xpl.red = false; + xp.red = true; + root = rotateRight(root, xp); + xpl = (xp = x.parent) == null ? null : xp.left; + } + if (xpl == null) + x = xp; + else { + TreeNode sl = xpl.left, sr = xpl.right; + if ((sl == null || !sl.red) && + (sr == null || !sr.red)) { + xpl.red = true; + x = xp; + } + else { + if (sl == null || !sl.red) { + if (sr != null) + sr.red = false; + xpl.red = true; + root = rotateLeft(root, xpl); + xpl = (xp = x.parent) == null ? + null : xp.left; + } + if (xpl != null) { + xpl.red = (xp == null) ? false : xp.red; + if ((sl = xpl.left) != null) + sl.red = false; + } + if (xp != null) { + xp.red = false; + root = rotateRight(root, xp); + } + x = root; + } + } + } + } + } + + /** + * Recursive invariant check + */ + static boolean checkInvariants(TreeNode t) { + TreeNode tp = t.parent, tl = t.left, tr = t.right, + tb = t.prev, tn = (TreeNode)t.next; + if (tb != null && tb.next != t) + return false; + if (tn != null && tn.prev != t) + return false; + if (tp != null && t != tp.left && t != tp.right) + return false; + if (tl != null && (tl.parent != t || tl.hash > t.hash)) + return false; + if (tr != null && (tr.parent != t || tr.hash < t.hash)) + return false; + if (t.red && tl != null && tl.red && tr != null && tr.red) + return false; + if (tl != null && !checkInvariants(tl)) + return false; + if (tr != null && !checkInvariants(tr)) + return false; + return true; + } + + private static final sun.misc.Unsafe U; + private static final long LOCKSTATE; + static { + try { + U = sun.misc.Unsafe.getUnsafe(); + Class k = TreeBin.class; + LOCKSTATE = U.objectFieldOffset + (k.getDeclaredField("lockState")); + } catch (Exception e) { + throw new Error(e); + } + } + } + + /* ----------------Table Traversal -------------- */ + + /** + * Records the table, its length, and current traversal index for a + * traverser that must process a region of a forwarded table before + * proceeding with current table. + */ + static final class TableStack { + int length; + int index; + Node[] tab; + TableStack next; + } + + /** + * Encapsulates traversal for methods such as containsValue; also + * serves as a base class for other iterators and spliterators. + * + * Method advance visits once each still-valid node that was + * reachable upon iterator construction. It might miss some that + * were added to a bin after the bin was visited, which is OK wrt + * consistency guarantees. Maintaining this property in the face + * of possible ongoing resizes requires a fair amount of + * bookkeeping state that is difficult to optimize away amidst + * volatile accesses. Even so, traversal maintains reasonable + * throughput. + * + * Normally, iteration proceeds bin-by-bin traversing lists. + * However, if the table has been resized, then all future steps + * must traverse both the bin at the current index as well as at + * (index + baseSize); and so on for further resizings. To + * paranoically cope with potential sharing by users of iterators + * across threads, iteration terminates if a bounds checks fails + * for a table read. + */ + static class Traverser { + Node[] tab; // current table; updated if resized + Node next; // the next entry to use + TableStack stack, spare; // to save/restore on ForwardingNodes + int index; // index of bin to use next + int baseIndex; // current index of initial table + int baseLimit; // index bound for initial table + final int baseSize; // initial table size + + Traverser(Node[] tab, int size, int index, int limit) { + this.tab = tab; + this.baseSize = size; + this.baseIndex = this.index = index; + this.baseLimit = limit; + this.next = null; + } + + /** + * Advances if possible, returning next valid node, or null if none. + */ + final Node advance() { + Node e; + if ((e = next) != null) + e = e.next; + for (;;) { + Node[] t; int i, n; // must use locals in checks + if (e != null) + return next = e; + if (baseIndex >= baseLimit || (t = tab) == null || + (n = t.length) <= (i = index) || i < 0) + return next = null; + if ((e = tabAt(t, i)) != null && e.hash < 0) { + if (e instanceof ForwardingNode) { + tab = ((ForwardingNode)e).nextTable; + e = null; + pushState(t, i, n); + continue; + } + else if (e instanceof TreeBin) + e = ((TreeBin)e).first; + else + e = null; + } + if (stack != null) + recoverState(n); + else if ((index = i + baseSize) >= n) + index = ++baseIndex; // visit upper slots if present + } + } + + /** + * Saves traversal state upon encountering a forwarding node. + */ + private void pushState(Node[] t, int i, int n) { + TableStack s = spare; // reuse if possible + if (s != null) + spare = s.next; + else + s = new TableStack(); + s.tab = t; + s.length = n; + s.index = i; + s.next = stack; + stack = s; + } + + /** + * Possibly pops traversal state. + * + * @param n length of current table + */ + private void recoverState(int n) { + TableStack s; int len; + while ((s = stack) != null && (index += (len = s.length)) >= n) { + n = len; + index = s.index; + tab = s.tab; + s.tab = null; + TableStack next = s.next; + s.next = spare; // save for reuse + stack = next; + spare = s; + } + if (s == null && (index += baseSize) >= n) + index = ++baseIndex; + } + } + + /** + * Base of key, value, and entry Iterators. Adds fields to + * Traverser to support iterator.remove. + */ + static class BaseIterator extends Traverser { + final ConcurrentHashMap map; + Node lastReturned; + BaseIterator(Node[] tab, int size, int index, int limit, + ConcurrentHashMap map) { + super(tab, size, index, limit); + this.map = map; + advance(); + } + + public final boolean hasNext() { return next != null; } + public final boolean hasMoreElements() { return next != null; } + + public final void remove() { + Node p; + if ((p = lastReturned) == null) + throw new IllegalStateException(); + lastReturned = null; + map.replaceNode(p.key, null, null); + } + } + + static final class KeyIterator extends BaseIterator + implements Iterator, Enumeration { + KeyIterator(Node[] tab, int index, int size, int limit, + ConcurrentHashMap map) { + super(tab, index, size, limit, map); + } + + public final K next() { + Node p; + if ((p = next) == null) + throw new NoSuchElementException(); + K k = p.key; + lastReturned = p; + advance(); + return k; + } + + public final K nextElement() { return next(); } + } + + static final class ValueIterator extends BaseIterator + implements Iterator, Enumeration { + ValueIterator(Node[] tab, int index, int size, int limit, + ConcurrentHashMap map) { + super(tab, index, size, limit, map); + } + + public final V next() { + Node p; + if ((p = next) == null) + throw new NoSuchElementException(); + V v = p.val; + lastReturned = p; + advance(); + return v; + } + + public final V nextElement() { return next(); } + } + + static final class EntryIterator extends BaseIterator + implements Iterator> { + EntryIterator(Node[] tab, int index, int size, int limit, + ConcurrentHashMap map) { + super(tab, index, size, limit, map); + } + + public final Map.Entry next() { + Node p; + if ((p = next) == null) + throw new NoSuchElementException(); + K k = p.key; + V v = p.val; + lastReturned = p; + advance(); + return new MapEntry(k, v, map); + } + } + + /** + * Exported Entry for EntryIterator + */ + static final class MapEntry implements Map.Entry { + final K key; // non-null + V val; // non-null + final ConcurrentHashMap map; + MapEntry(K key, V val, ConcurrentHashMap map) { + this.key = key; + this.val = val; + this.map = map; + } + public K getKey() { return key; } + public V getValue() { return val; } + public int hashCode() { return key.hashCode() ^ val.hashCode(); } + public String toString() { return key + "=" + val; } + + public boolean equals(Object o) { + Object k, v; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (v = e.getValue()) != null && + (k == key || k.equals(key)) && + (v == val || v.equals(val))); + } + + /** + * Sets our entry's value and writes through to the map. The + * value to return is somewhat arbitrary here. Since we do not + * necessarily track asynchronous changes, the most recent + * "previous" value could be different from what we return (or + * could even have been removed, in which case the put will + * re-establish). We do not and cannot guarantee more. + */ + public V setValue(V value) { + if (value == null) throw new NullPointerException(); + V v = val; + val = value; + map.put(key, value); + return v; + } + } + + static final class KeySpliterator extends Traverser + implements Spliterator { + long est; // size estimate + KeySpliterator(Node[] tab, int size, int index, int limit, + long est) { + super(tab, size, index, limit); + this.est = est; + } + + public Spliterator trySplit() { + int i, f, h; + return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : + new KeySpliterator(tab, baseSize, baseLimit = h, + f, est >>>= 1); + } + + public void forEachRemaining(Consumer action) { + if (action == null) throw new NullPointerException(); + for (Node p; (p = advance()) != null;) + action.accept(p.key); + } + + public boolean tryAdvance(Consumer action) { + if (action == null) throw new NullPointerException(); + Node p; + if ((p = advance()) == null) + return false; + action.accept(p.key); + return true; + } + + public long estimateSize() { return est; } + + public int characteristics() { + return Spliterator.DISTINCT | Spliterator.CONCURRENT | + Spliterator.NONNULL; + } + } + + static final class ValueSpliterator extends Traverser + implements Spliterator { + long est; // size estimate + ValueSpliterator(Node[] tab, int size, int index, int limit, + long est) { + super(tab, size, index, limit); + this.est = est; + } + + public Spliterator trySplit() { + int i, f, h; + return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : + new ValueSpliterator(tab, baseSize, baseLimit = h, + f, est >>>= 1); + } + + public void forEachRemaining(Consumer action) { + if (action == null) throw new NullPointerException(); + for (Node p; (p = advance()) != null;) + action.accept(p.val); + } + + public boolean tryAdvance(Consumer action) { + if (action == null) throw new NullPointerException(); + Node p; + if ((p = advance()) == null) + return false; + action.accept(p.val); + return true; + } + + public long estimateSize() { return est; } + + public int characteristics() { + return Spliterator.CONCURRENT | Spliterator.NONNULL; + } + } + + static final class EntrySpliterator extends Traverser + implements Spliterator> { + final ConcurrentHashMap map; // To export MapEntry + long est; // size estimate + EntrySpliterator(Node[] tab, int size, int index, int limit, + long est, ConcurrentHashMap map) { + super(tab, size, index, limit); + this.map = map; + this.est = est; + } + + public Spliterator> trySplit() { + int i, f, h; + return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : + new EntrySpliterator(tab, baseSize, baseLimit = h, + f, est >>>= 1, map); + } + + public void forEachRemaining(Consumer> action) { + if (action == null) throw new NullPointerException(); + for (Node p; (p = advance()) != null; ) + action.accept(new MapEntry(p.key, p.val, map)); + } + + public boolean tryAdvance(Consumer> action) { + if (action == null) throw new NullPointerException(); + Node p; + if ((p = advance()) == null) + return false; + action.accept(new MapEntry(p.key, p.val, map)); + return true; + } + + public long estimateSize() { return est; } + + public int characteristics() { + return Spliterator.DISTINCT | Spliterator.CONCURRENT | + Spliterator.NONNULL; + } + } + + // Parallel bulk operations + + /** + * Computes initial batch value for bulk tasks. The returned value + * is approximately exp2 of the number of times (minus one) to + * split task by two before executing leaf action. This value is + * faster to compute and more convenient to use as a guide to + * splitting than is the depth, since it is used while dividing by + * two anyway. + */ + final int batchFor(long b) { + long n; + if (b == Long.MAX_VALUE || (n = sumCount()) <= 1L || n < b) + return 0; + int sp = ForkJoinPool.getCommonPoolParallelism() << 2; // slack of 4 + return (b <= 0L || (n /= b) >= sp) ? sp : (int)n; + } + + /** + * Performs the given action for each (key, value). + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param action the action + * @since 1.8 + */ + public void forEach(long parallelismThreshold, + BiConsumer action) { + if (action == null) throw new NullPointerException(); + new ForEachMappingTask + (null, batchFor(parallelismThreshold), 0, 0, table, + action).invoke(); + } + + /** + * Performs the given action for each non-null transformation + * of each (key, value). + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element, or null if there is no transformation (in + * which case the action is not applied) + * @param action the action + * @param the return type of the transformer + * @since 1.8 + */ + public void forEach(long parallelismThreshold, + BiFunction transformer, + Consumer action) { + if (transformer == null || action == null) + throw new NullPointerException(); + new ForEachTransformedMappingTask + (null, batchFor(parallelismThreshold), 0, 0, table, + transformer, action).invoke(); + } + + /** + * Returns a non-null result from applying the given search + * function on each (key, value), or null if none. Upon + * success, further element processing is suppressed and the + * results of any other parallel invocations of the search + * function are ignored. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param searchFunction a function returning a non-null + * result on success, else null + * @param the return type of the search function + * @return a non-null result from applying the given search + * function on each (key, value), or null if none + * @since 1.8 + */ + public U search(long parallelismThreshold, + BiFunction searchFunction) { + if (searchFunction == null) throw new NullPointerException(); + return new SearchMappingsTask + (null, batchFor(parallelismThreshold), 0, 0, table, + searchFunction, new AtomicReference()).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all (key, value) pairs using the given reducer to + * combine values, or null if none. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element, or null if there is no transformation (in + * which case it is not combined) + * @param reducer a commutative associative combining function + * @param the return type of the transformer + * @return the result of accumulating the given transformation + * of all (key, value) pairs + * @since 1.8 + */ + public U reduce(long parallelismThreshold, + BiFunction transformer, + BiFunction reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceMappingsTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all (key, value) pairs using the given reducer to + * combine values, and the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all (key, value) pairs + * @since 1.8 + */ + public double reduceToDouble(long parallelismThreshold, + ToDoubleBiFunction transformer, + double basis, + DoubleBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceMappingsToDoubleTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all (key, value) pairs using the given reducer to + * combine values, and the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all (key, value) pairs + * @since 1.8 + */ + public long reduceToLong(long parallelismThreshold, + ToLongBiFunction transformer, + long basis, + LongBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceMappingsToLongTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all (key, value) pairs using the given reducer to + * combine values, and the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all (key, value) pairs + * @since 1.8 + */ + public int reduceToInt(long parallelismThreshold, + ToIntBiFunction transformer, + int basis, + IntBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceMappingsToIntTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Performs the given action for each key. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param action the action + * @since 1.8 + */ + public void forEachKey(long parallelismThreshold, + Consumer action) { + if (action == null) throw new NullPointerException(); + new ForEachKeyTask + (null, batchFor(parallelismThreshold), 0, 0, table, + action).invoke(); + } + + /** + * Performs the given action for each non-null transformation + * of each key. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element, or null if there is no transformation (in + * which case the action is not applied) + * @param action the action + * @param the return type of the transformer + * @since 1.8 + */ + public void forEachKey(long parallelismThreshold, + Function transformer, + Consumer action) { + if (transformer == null || action == null) + throw new NullPointerException(); + new ForEachTransformedKeyTask + (null, batchFor(parallelismThreshold), 0, 0, table, + transformer, action).invoke(); + } + + /** + * Returns a non-null result from applying the given search + * function on each key, or null if none. Upon success, + * further element processing is suppressed and the results of + * any other parallel invocations of the search function are + * ignored. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param searchFunction a function returning a non-null + * result on success, else null + * @param the return type of the search function + * @return a non-null result from applying the given search + * function on each key, or null if none + * @since 1.8 + */ + public U searchKeys(long parallelismThreshold, + Function searchFunction) { + if (searchFunction == null) throw new NullPointerException(); + return new SearchKeysTask + (null, batchFor(parallelismThreshold), 0, 0, table, + searchFunction, new AtomicReference()).invoke(); + } + + /** + * Returns the result of accumulating all keys using the given + * reducer to combine values, or null if none. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param reducer a commutative associative combining function + * @return the result of accumulating all keys using the given + * reducer to combine values, or null if none + * @since 1.8 + */ + public K reduceKeys(long parallelismThreshold, + BiFunction reducer) { + if (reducer == null) throw new NullPointerException(); + return new ReduceKeysTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all keys using the given reducer to combine values, or + * null if none. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element, or null if there is no transformation (in + * which case it is not combined) + * @param reducer a commutative associative combining function + * @param the return type of the transformer + * @return the result of accumulating the given transformation + * of all keys + * @since 1.8 + */ + public U reduceKeys(long parallelismThreshold, + Function transformer, + BiFunction reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceKeysTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all keys using the given reducer to combine values, and + * the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all keys + * @since 1.8 + */ + public double reduceKeysToDouble(long parallelismThreshold, + ToDoubleFunction transformer, + double basis, + DoubleBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceKeysToDoubleTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all keys using the given reducer to combine values, and + * the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all keys + * @since 1.8 + */ + public long reduceKeysToLong(long parallelismThreshold, + ToLongFunction transformer, + long basis, + LongBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceKeysToLongTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all keys using the given reducer to combine values, and + * the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all keys + * @since 1.8 + */ + public int reduceKeysToInt(long parallelismThreshold, + ToIntFunction transformer, + int basis, + IntBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceKeysToIntTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Performs the given action for each value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param action the action + * @since 1.8 + */ + public void forEachValue(long parallelismThreshold, + Consumer action) { + if (action == null) + throw new NullPointerException(); + new ForEachValueTask + (null, batchFor(parallelismThreshold), 0, 0, table, + action).invoke(); + } + + /** + * Performs the given action for each non-null transformation + * of each value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element, or null if there is no transformation (in + * which case the action is not applied) + * @param action the action + * @param the return type of the transformer + * @since 1.8 + */ + public void forEachValue(long parallelismThreshold, + Function transformer, + Consumer action) { + if (transformer == null || action == null) + throw new NullPointerException(); + new ForEachTransformedValueTask + (null, batchFor(parallelismThreshold), 0, 0, table, + transformer, action).invoke(); + } + + /** + * Returns a non-null result from applying the given search + * function on each value, or null if none. Upon success, + * further element processing is suppressed and the results of + * any other parallel invocations of the search function are + * ignored. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param searchFunction a function returning a non-null + * result on success, else null + * @param the return type of the search function + * @return a non-null result from applying the given search + * function on each value, or null if none + * @since 1.8 + */ + public U searchValues(long parallelismThreshold, + Function searchFunction) { + if (searchFunction == null) throw new NullPointerException(); + return new SearchValuesTask + (null, batchFor(parallelismThreshold), 0, 0, table, + searchFunction, new AtomicReference()).invoke(); + } + + /** + * Returns the result of accumulating all values using the + * given reducer to combine values, or null if none. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param reducer a commutative associative combining function + * @return the result of accumulating all values + * @since 1.8 + */ + public V reduceValues(long parallelismThreshold, + BiFunction reducer) { + if (reducer == null) throw new NullPointerException(); + return new ReduceValuesTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all values using the given reducer to combine values, or + * null if none. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element, or null if there is no transformation (in + * which case it is not combined) + * @param reducer a commutative associative combining function + * @param the return type of the transformer + * @return the result of accumulating the given transformation + * of all values + * @since 1.8 + */ + public U reduceValues(long parallelismThreshold, + Function transformer, + BiFunction reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceValuesTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all values using the given reducer to combine values, + * and the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all values + * @since 1.8 + */ + public double reduceValuesToDouble(long parallelismThreshold, + ToDoubleFunction transformer, + double basis, + DoubleBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceValuesToDoubleTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all values using the given reducer to combine values, + * and the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all values + * @since 1.8 + */ + public long reduceValuesToLong(long parallelismThreshold, + ToLongFunction transformer, + long basis, + LongBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceValuesToLongTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all values using the given reducer to combine values, + * and the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all values + * @since 1.8 + */ + public int reduceValuesToInt(long parallelismThreshold, + ToIntFunction transformer, + int basis, + IntBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceValuesToIntTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Performs the given action for each entry. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param action the action + * @since 1.8 + */ + public void forEachEntry(long parallelismThreshold, + Consumer> action) { + if (action == null) throw new NullPointerException(); + new ForEachEntryTask(null, batchFor(parallelismThreshold), 0, 0, table, + action).invoke(); + } + + /** + * Performs the given action for each non-null transformation + * of each entry. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element, or null if there is no transformation (in + * which case the action is not applied) + * @param action the action + * @param the return type of the transformer + * @since 1.8 + */ + public void forEachEntry(long parallelismThreshold, + Function, ? extends U> transformer, + Consumer action) { + if (transformer == null || action == null) + throw new NullPointerException(); + new ForEachTransformedEntryTask + (null, batchFor(parallelismThreshold), 0, 0, table, + transformer, action).invoke(); + } + + /** + * Returns a non-null result from applying the given search + * function on each entry, or null if none. Upon success, + * further element processing is suppressed and the results of + * any other parallel invocations of the search function are + * ignored. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param searchFunction a function returning a non-null + * result on success, else null + * @param the return type of the search function + * @return a non-null result from applying the given search + * function on each entry, or null if none + * @since 1.8 + */ + public U searchEntries(long parallelismThreshold, + Function, ? extends U> searchFunction) { + if (searchFunction == null) throw new NullPointerException(); + return new SearchEntriesTask + (null, batchFor(parallelismThreshold), 0, 0, table, + searchFunction, new AtomicReference()).invoke(); + } + + /** + * Returns the result of accumulating all entries using the + * given reducer to combine values, or null if none. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param reducer a commutative associative combining function + * @return the result of accumulating all entries + * @since 1.8 + */ + public Map.Entry reduceEntries(long parallelismThreshold, + BiFunction, Map.Entry, ? extends Map.Entry> reducer) { + if (reducer == null) throw new NullPointerException(); + return new ReduceEntriesTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all entries using the given reducer to combine values, + * or null if none. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element, or null if there is no transformation (in + * which case it is not combined) + * @param reducer a commutative associative combining function + * @param the return type of the transformer + * @return the result of accumulating the given transformation + * of all entries + * @since 1.8 + */ + public U reduceEntries(long parallelismThreshold, + Function, ? extends U> transformer, + BiFunction reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceEntriesTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all entries using the given reducer to combine values, + * and the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all entries + * @since 1.8 + */ + public double reduceEntriesToDouble(long parallelismThreshold, + ToDoubleFunction> transformer, + double basis, + DoubleBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceEntriesToDoubleTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all entries using the given reducer to combine values, + * and the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all entries + * @since 1.8 + */ + public long reduceEntriesToLong(long parallelismThreshold, + ToLongFunction> transformer, + long basis, + LongBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceEntriesToLongTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + /** + * Returns the result of accumulating the given transformation + * of all entries using the given reducer to combine values, + * and the given basis as an identity value. + * + * @param parallelismThreshold the (estimated) number of elements + * needed for this operation to be executed in parallel + * @param transformer a function returning the transformation + * for an element + * @param basis the identity (initial default value) for the reduction + * @param reducer a commutative associative combining function + * @return the result of accumulating the given transformation + * of all entries + * @since 1.8 + */ + public int reduceEntriesToInt(long parallelismThreshold, + ToIntFunction> transformer, + int basis, + IntBinaryOperator reducer) { + if (transformer == null || reducer == null) + throw new NullPointerException(); + return new MapReduceEntriesToIntTask + (null, batchFor(parallelismThreshold), 0, 0, table, + null, transformer, basis, reducer).invoke(); + } + + + /* ----------------Views -------------- */ + + /** + * Base class for views. + */ + abstract static class CollectionView + implements Collection, java.io.Serializable { + private static final long serialVersionUID = 7249069246763182397L; + final ConcurrentHashMap map; + CollectionView(ConcurrentHashMap map) { this.map = map; } + + /** + * Returns the map backing this view. + * + * @return the map backing this view + */ + public ConcurrentHashMap getMap() { return map; } + + /** + * Removes all of the elements from this view, by removing all + * the mappings from the map backing this view. + */ + public final void clear() { map.clear(); } + public final int size() { return map.size(); } + public final boolean isEmpty() { return map.isEmpty(); } + + // implementations below rely on concrete classes supplying these + // abstract methods + /** + * Returns an iterator over the elements in this collection. + * + *

The returned iterator is + * weakly consistent. + * + * @return an iterator over the elements in this collection + */ + public abstract Iterator iterator(); + public abstract boolean contains(Object o); + public abstract boolean remove(Object o); + + private static final String oomeMsg = "Required array size too large"; + + public final Object[] toArray() { + long sz = map.mappingCount(); + if (sz > MAX_ARRAY_SIZE) + throw new OutOfMemoryError(oomeMsg); + int n = (int)sz; + Object[] r = new Object[n]; + int i = 0; + for (E e : this) { + if (i == n) { + if (n >= MAX_ARRAY_SIZE) + throw new OutOfMemoryError(oomeMsg); + if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) + n = MAX_ARRAY_SIZE; + else + n += (n >>> 1) + 1; + r = Arrays.copyOf(r, n); + } + r[i++] = e; + } + return (i == n) ? r : Arrays.copyOf(r, i); + } + + @SuppressWarnings("unchecked") + public final T[] toArray(T[] a) { + long sz = map.mappingCount(); + if (sz > MAX_ARRAY_SIZE) + throw new OutOfMemoryError(oomeMsg); + int m = (int)sz; + T[] r = (a.length >= m) ? a : + (T[])java.lang.reflect.Array + .newInstance(a.getClass().getComponentType(), m); + int n = r.length; + int i = 0; + for (E e : this) { + if (i == n) { + if (n >= MAX_ARRAY_SIZE) + throw new OutOfMemoryError(oomeMsg); + if (n >= MAX_ARRAY_SIZE - (MAX_ARRAY_SIZE >>> 1) - 1) + n = MAX_ARRAY_SIZE; + else + n += (n >>> 1) + 1; + r = Arrays.copyOf(r, n); + } + r[i++] = (T)e; + } + if (a == r && i < n) { + r[i] = null; // null-terminate + return r; + } + return (i == n) ? r : Arrays.copyOf(r, i); + } + + /** + * Returns a string representation of this collection. + * The string representation consists of the string representations + * of the collection's elements in the order they are returned by + * its iterator, enclosed in square brackets ({@code "[]"}). + * Adjacent elements are separated by the characters {@code ", "} + * (comma and space). Elements are converted to strings as by + * {@link String#valueOf(Object)}. + * + * @return a string representation of this collection + */ + public final String toString() { + StringBuilder sb = new StringBuilder(); + sb.append('['); + Iterator it = iterator(); + if (it.hasNext()) { + for (;;) { + Object e = it.next(); + sb.append(e == this ? "(this Collection)" : e); + if (!it.hasNext()) + break; + sb.append(',').append(' '); + } + } + return sb.append(']').toString(); + } + + public final boolean containsAll(Collection c) { + if (c != this) { + for (Object e : c) { + if (e == null || !contains(e)) + return false; + } + } + return true; + } + + public final boolean removeAll(Collection c) { + if (c == null) throw new NullPointerException(); + boolean modified = false; + for (Iterator it = iterator(); it.hasNext();) { + if (c.contains(it.next())) { + it.remove(); + modified = true; + } + } + return modified; + } + + public final boolean retainAll(Collection c) { + if (c == null) throw new NullPointerException(); + boolean modified = false; + for (Iterator it = iterator(); it.hasNext();) { + if (!c.contains(it.next())) { + it.remove(); + modified = true; + } + } + return modified; + } + + } + + /** + * A view of a ConcurrentHashMap as a {@link Set} of keys, in + * which additions may optionally be enabled by mapping to a + * common value. This class cannot be directly instantiated. + * See {@link #keySet() keySet()}, + * {@link #keySet(Object) keySet(V)}, + * {@link #newKeySet() newKeySet()}, + * {@link #newKeySet(int) newKeySet(int)}. + * + * @since 1.8 + */ + public static class KeySetView extends CollectionView + implements Set, java.io.Serializable { + private static final long serialVersionUID = 7249069246763182397L; + private final V value; + KeySetView(ConcurrentHashMap map, V value) { // non-public + super(map); + this.value = value; + } + + /** + * Returns the default mapped value for additions, + * or {@code null} if additions are not supported. + * + * @return the default mapped value for additions, or {@code null} + * if not supported + */ + public V getMappedValue() { return value; } + + /** + * {@inheritDoc} + * @throws NullPointerException if the specified key is null + */ + public boolean contains(Object o) { return map.containsKey(o); } + + /** + * Removes the key from this map view, by removing the key (and its + * corresponding value) from the backing map. This method does + * nothing if the key is not in the map. + * + * @param o the key to be removed from the backing map + * @return {@code true} if the backing map contained the specified key + * @throws NullPointerException if the specified key is null + */ + public boolean remove(Object o) { return map.remove(o) != null; } + + /** + * @return an iterator over the keys of the backing map + */ + public Iterator iterator() { + Node[] t; + ConcurrentHashMap m = map; + int f = (t = m.table) == null ? 0 : t.length; + return new KeyIterator(t, f, 0, f, m); + } + + /** + * Adds the specified key to this set view by mapping the key to + * the default mapped value in the backing map, if defined. + * + * @param e key to be added + * @return {@code true} if this set changed as a result of the call + * @throws NullPointerException if the specified key is null + * @throws UnsupportedOperationException if no default mapped value + * for additions was provided + */ + public boolean add(K e) { + V v; + if ((v = value) == null) + throw new UnsupportedOperationException(); + return map.putVal(e, v, true) == null; + } + + /** + * Adds all of the elements in the specified collection to this set, + * as if by calling {@link #add} on each one. + * + * @param c the elements to be inserted into this set + * @return {@code true} if this set changed as a result of the call + * @throws NullPointerException if the collection or any of its + * elements are {@code null} + * @throws UnsupportedOperationException if no default mapped value + * for additions was provided + */ + public boolean addAll(Collection c) { + boolean added = false; + V v; + if ((v = value) == null) + throw new UnsupportedOperationException(); + for (K e : c) { + if (map.putVal(e, v, true) == null) + added = true; + } + return added; + } + + public int hashCode() { + int h = 0; + for (K e : this) + h += e.hashCode(); + return h; + } + + public boolean equals(Object o) { + Set c; + return ((o instanceof Set) && + ((c = (Set)o) == this || + (containsAll(c) && c.containsAll(this)))); + } + + public Spliterator spliterator() { + Node[] t; + ConcurrentHashMap m = map; + long n = m.sumCount(); + int f = (t = m.table) == null ? 0 : t.length; + return new KeySpliterator(t, f, 0, f, n < 0L ? 0L : n); + } + + public void forEach(Consumer action) { + if (action == null) throw new NullPointerException(); + Node[] t; + if ((t = map.table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) + action.accept(p.key); + } + } + } + + /** + * A view of a ConcurrentHashMap as a {@link Collection} of + * values, in which additions are disabled. This class cannot be + * directly instantiated. See {@link #values()}. + */ + static final class ValuesView extends CollectionView + implements Collection, java.io.Serializable { + private static final long serialVersionUID = 2249069246763182397L; + ValuesView(ConcurrentHashMap map) { super(map); } + public final boolean contains(Object o) { + return map.containsValue(o); + } + + public final boolean remove(Object o) { + if (o != null) { + for (Iterator it = iterator(); it.hasNext();) { + if (o.equals(it.next())) { + it.remove(); + return true; + } + } + } + return false; + } + + public final Iterator iterator() { + ConcurrentHashMap m = map; + Node[] t; + int f = (t = m.table) == null ? 0 : t.length; + return new ValueIterator(t, f, 0, f, m); + } + + public final boolean add(V e) { + throw new UnsupportedOperationException(); + } + public final boolean addAll(Collection c) { + throw new UnsupportedOperationException(); + } + + public Spliterator spliterator() { + Node[] t; + ConcurrentHashMap m = map; + long n = m.sumCount(); + int f = (t = m.table) == null ? 0 : t.length; + return new ValueSpliterator(t, f, 0, f, n < 0L ? 0L : n); + } + + public void forEach(Consumer action) { + if (action == null) throw new NullPointerException(); + Node[] t; + if ((t = map.table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) + action.accept(p.val); + } + } + } + + /** + * A view of a ConcurrentHashMap as a {@link Set} of (key, value) + * entries. This class cannot be directly instantiated. See + * {@link #entrySet()}. + */ + static final class EntrySetView extends CollectionView> + implements Set>, java.io.Serializable { + private static final long serialVersionUID = 2249069246763182397L; + EntrySetView(ConcurrentHashMap map) { super(map); } + + public boolean contains(Object o) { + Object k, v, r; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (r = map.get(k)) != null && + (v = e.getValue()) != null && + (v == r || v.equals(r))); + } + + public boolean remove(Object o) { + Object k, v; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (v = e.getValue()) != null && + map.remove(k, v)); + } + + /** + * @return an iterator over the entries of the backing map + */ + public Iterator> iterator() { + ConcurrentHashMap m = map; + Node[] t; + int f = (t = m.table) == null ? 0 : t.length; + return new EntryIterator(t, f, 0, f, m); + } + + public boolean add(Entry e) { + return map.putVal(e.getKey(), e.getValue(), false) == null; + } + + public boolean addAll(Collection> c) { + boolean added = false; + for (Entry e : c) { + if (add(e)) + added = true; + } + return added; + } + + public final int hashCode() { + int h = 0; + Node[] t; + if ((t = map.table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + h += p.hashCode(); + } + } + return h; + } + + public final boolean equals(Object o) { + Set c; + return ((o instanceof Set) && + ((c = (Set)o) == this || + (containsAll(c) && c.containsAll(this)))); + } + + public Spliterator> spliterator() { + Node[] t; + ConcurrentHashMap m = map; + long n = m.sumCount(); + int f = (t = m.table) == null ? 0 : t.length; + return new EntrySpliterator(t, f, 0, f, n < 0L ? 0L : n, m); + } + + public void forEach(Consumer> action) { + if (action == null) throw new NullPointerException(); + Node[] t; + if ((t = map.table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) + action.accept(new MapEntry(p.key, p.val, map)); + } + } + + } + + // ------------------------------------------------------- + + /** + * Base class for bulk tasks. Repeats some fields and code from + * class Traverser, because we need to subclass CountedCompleter. + */ + @SuppressWarnings("serial") + abstract static class BulkTask extends CountedCompleter { + Node[] tab; // same as Traverser + Node next; + TableStack stack, spare; + int index; + int baseIndex; + int baseLimit; + final int baseSize; + int batch; // split control + + BulkTask(BulkTask par, int b, int i, int f, Node[] t) { + super(par); + this.batch = b; + this.index = this.baseIndex = i; + if ((this.tab = t) == null) + this.baseSize = this.baseLimit = 0; + else if (par == null) + this.baseSize = this.baseLimit = t.length; + else { + this.baseLimit = f; + this.baseSize = par.baseSize; + } + } + + /** + * Same as Traverser version + */ + final Node advance() { + Node e; + if ((e = next) != null) + e = e.next; + for (;;) { + Node[] t; int i, n; + if (e != null) + return next = e; + if (baseIndex >= baseLimit || (t = tab) == null || + (n = t.length) <= (i = index) || i < 0) + return next = null; + if ((e = tabAt(t, i)) != null && e.hash < 0) { + if (e instanceof ForwardingNode) { + tab = ((ForwardingNode)e).nextTable; + e = null; + pushState(t, i, n); + continue; + } + else if (e instanceof TreeBin) + e = ((TreeBin)e).first; + else + e = null; + } + if (stack != null) + recoverState(n); + else if ((index = i + baseSize) >= n) + index = ++baseIndex; + } + } + + private void pushState(Node[] t, int i, int n) { + TableStack s = spare; + if (s != null) + spare = s.next; + else + s = new TableStack(); + s.tab = t; + s.length = n; + s.index = i; + s.next = stack; + stack = s; + } + + private void recoverState(int n) { + TableStack s; int len; + while ((s = stack) != null && (index += (len = s.length)) >= n) { + n = len; + index = s.index; + tab = s.tab; + s.tab = null; + TableStack next = s.next; + s.next = spare; // save for reuse + stack = next; + spare = s; + } + if (s == null && (index += baseSize) >= n) + index = ++baseIndex; + } + } + + /* + * Task classes. Coded in a regular but ugly format/style to + * simplify checks that each variant differs in the right way from + * others. The null screenings exist because compilers cannot tell + * that we've already null-checked task arguments, so we force + * simplest hoisted bypass to help avoid convoluted traps. + */ + @SuppressWarnings("serial") + static final class ForEachKeyTask + extends BulkTask { + final Consumer action; + ForEachKeyTask + (BulkTask p, int b, int i, int f, Node[] t, + Consumer action) { + super(p, b, i, f, t); + this.action = action; + } + public final void compute() { + final Consumer action; + if ((action = this.action) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + new ForEachKeyTask + (this, batch >>>= 1, baseLimit = h, f, tab, + action).fork(); + } + for (Node p; (p = advance()) != null;) + action.accept(p.key); + propagateCompletion(); + } + } + } + + @SuppressWarnings("serial") + static final class ForEachValueTask + extends BulkTask { + final Consumer action; + ForEachValueTask + (BulkTask p, int b, int i, int f, Node[] t, + Consumer action) { + super(p, b, i, f, t); + this.action = action; + } + public final void compute() { + final Consumer action; + if ((action = this.action) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + new ForEachValueTask + (this, batch >>>= 1, baseLimit = h, f, tab, + action).fork(); + } + for (Node p; (p = advance()) != null;) + action.accept(p.val); + propagateCompletion(); + } + } + } + + @SuppressWarnings("serial") + static final class ForEachEntryTask + extends BulkTask { + final Consumer> action; + ForEachEntryTask + (BulkTask p, int b, int i, int f, Node[] t, + Consumer> action) { + super(p, b, i, f, t); + this.action = action; + } + public final void compute() { + final Consumer> action; + if ((action = this.action) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + new ForEachEntryTask + (this, batch >>>= 1, baseLimit = h, f, tab, + action).fork(); + } + for (Node p; (p = advance()) != null; ) + action.accept(p); + propagateCompletion(); + } + } + } + + @SuppressWarnings("serial") + static final class ForEachMappingTask + extends BulkTask { + final BiConsumer action; + ForEachMappingTask + (BulkTask p, int b, int i, int f, Node[] t, + BiConsumer action) { + super(p, b, i, f, t); + this.action = action; + } + public final void compute() { + final BiConsumer action; + if ((action = this.action) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + new ForEachMappingTask + (this, batch >>>= 1, baseLimit = h, f, tab, + action).fork(); + } + for (Node p; (p = advance()) != null; ) + action.accept(p.key, p.val); + propagateCompletion(); + } + } + } + + @SuppressWarnings("serial") + static final class ForEachTransformedKeyTask + extends BulkTask { + final Function transformer; + final Consumer action; + ForEachTransformedKeyTask + (BulkTask p, int b, int i, int f, Node[] t, + Function transformer, Consumer action) { + super(p, b, i, f, t); + this.transformer = transformer; this.action = action; + } + public final void compute() { + final Function transformer; + final Consumer action; + if ((transformer = this.transformer) != null && + (action = this.action) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + new ForEachTransformedKeyTask + (this, batch >>>= 1, baseLimit = h, f, tab, + transformer, action).fork(); + } + for (Node p; (p = advance()) != null; ) { + U u; + if ((u = transformer.apply(p.key)) != null) + action.accept(u); + } + propagateCompletion(); + } + } + } + + @SuppressWarnings("serial") + static final class ForEachTransformedValueTask + extends BulkTask { + final Function transformer; + final Consumer action; + ForEachTransformedValueTask + (BulkTask p, int b, int i, int f, Node[] t, + Function transformer, Consumer action) { + super(p, b, i, f, t); + this.transformer = transformer; this.action = action; + } + public final void compute() { + final Function transformer; + final Consumer action; + if ((transformer = this.transformer) != null && + (action = this.action) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + new ForEachTransformedValueTask + (this, batch >>>= 1, baseLimit = h, f, tab, + transformer, action).fork(); + } + for (Node p; (p = advance()) != null; ) { + U u; + if ((u = transformer.apply(p.val)) != null) + action.accept(u); + } + propagateCompletion(); + } + } + } + + @SuppressWarnings("serial") + static final class ForEachTransformedEntryTask + extends BulkTask { + final Function, ? extends U> transformer; + final Consumer action; + ForEachTransformedEntryTask + (BulkTask p, int b, int i, int f, Node[] t, + Function, ? extends U> transformer, Consumer action) { + super(p, b, i, f, t); + this.transformer = transformer; this.action = action; + } + public final void compute() { + final Function, ? extends U> transformer; + final Consumer action; + if ((transformer = this.transformer) != null && + (action = this.action) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + new ForEachTransformedEntryTask + (this, batch >>>= 1, baseLimit = h, f, tab, + transformer, action).fork(); + } + for (Node p; (p = advance()) != null; ) { + U u; + if ((u = transformer.apply(p)) != null) + action.accept(u); + } + propagateCompletion(); + } + } + } + + @SuppressWarnings("serial") + static final class ForEachTransformedMappingTask + extends BulkTask { + final BiFunction transformer; + final Consumer action; + ForEachTransformedMappingTask + (BulkTask p, int b, int i, int f, Node[] t, + BiFunction transformer, + Consumer action) { + super(p, b, i, f, t); + this.transformer = transformer; this.action = action; + } + public final void compute() { + final BiFunction transformer; + final Consumer action; + if ((transformer = this.transformer) != null && + (action = this.action) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + new ForEachTransformedMappingTask + (this, batch >>>= 1, baseLimit = h, f, tab, + transformer, action).fork(); + } + for (Node p; (p = advance()) != null; ) { + U u; + if ((u = transformer.apply(p.key, p.val)) != null) + action.accept(u); + } + propagateCompletion(); + } + } + } + + @SuppressWarnings("serial") + static final class SearchKeysTask + extends BulkTask { + final Function searchFunction; + final AtomicReference result; + SearchKeysTask + (BulkTask p, int b, int i, int f, Node[] t, + Function searchFunction, + AtomicReference result) { + super(p, b, i, f, t); + this.searchFunction = searchFunction; this.result = result; + } + public final U getRawResult() { return result.get(); } + public final void compute() { + final Function searchFunction; + final AtomicReference result; + if ((searchFunction = this.searchFunction) != null && + (result = this.result) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + if (result.get() != null) + return; + addToPendingCount(1); + new SearchKeysTask + (this, batch >>>= 1, baseLimit = h, f, tab, + searchFunction, result).fork(); + } + while (result.get() == null) { + U u; + Node p; + if ((p = advance()) == null) { + propagateCompletion(); + break; + } + if ((u = searchFunction.apply(p.key)) != null) { + if (result.compareAndSet(null, u)) + quietlyCompleteRoot(); + break; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class SearchValuesTask + extends BulkTask { + final Function searchFunction; + final AtomicReference result; + SearchValuesTask + (BulkTask p, int b, int i, int f, Node[] t, + Function searchFunction, + AtomicReference result) { + super(p, b, i, f, t); + this.searchFunction = searchFunction; this.result = result; + } + public final U getRawResult() { return result.get(); } + public final void compute() { + final Function searchFunction; + final AtomicReference result; + if ((searchFunction = this.searchFunction) != null && + (result = this.result) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + if (result.get() != null) + return; + addToPendingCount(1); + new SearchValuesTask + (this, batch >>>= 1, baseLimit = h, f, tab, + searchFunction, result).fork(); + } + while (result.get() == null) { + U u; + Node p; + if ((p = advance()) == null) { + propagateCompletion(); + break; + } + if ((u = searchFunction.apply(p.val)) != null) { + if (result.compareAndSet(null, u)) + quietlyCompleteRoot(); + break; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class SearchEntriesTask + extends BulkTask { + final Function, ? extends U> searchFunction; + final AtomicReference result; + SearchEntriesTask + (BulkTask p, int b, int i, int f, Node[] t, + Function, ? extends U> searchFunction, + AtomicReference result) { + super(p, b, i, f, t); + this.searchFunction = searchFunction; this.result = result; + } + public final U getRawResult() { return result.get(); } + public final void compute() { + final Function, ? extends U> searchFunction; + final AtomicReference result; + if ((searchFunction = this.searchFunction) != null && + (result = this.result) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + if (result.get() != null) + return; + addToPendingCount(1); + new SearchEntriesTask + (this, batch >>>= 1, baseLimit = h, f, tab, + searchFunction, result).fork(); + } + while (result.get() == null) { + U u; + Node p; + if ((p = advance()) == null) { + propagateCompletion(); + break; + } + if ((u = searchFunction.apply(p)) != null) { + if (result.compareAndSet(null, u)) + quietlyCompleteRoot(); + return; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class SearchMappingsTask + extends BulkTask { + final BiFunction searchFunction; + final AtomicReference result; + SearchMappingsTask + (BulkTask p, int b, int i, int f, Node[] t, + BiFunction searchFunction, + AtomicReference result) { + super(p, b, i, f, t); + this.searchFunction = searchFunction; this.result = result; + } + public final U getRawResult() { return result.get(); } + public final void compute() { + final BiFunction searchFunction; + final AtomicReference result; + if ((searchFunction = this.searchFunction) != null && + (result = this.result) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + if (result.get() != null) + return; + addToPendingCount(1); + new SearchMappingsTask + (this, batch >>>= 1, baseLimit = h, f, tab, + searchFunction, result).fork(); + } + while (result.get() == null) { + U u; + Node p; + if ((p = advance()) == null) { + propagateCompletion(); + break; + } + if ((u = searchFunction.apply(p.key, p.val)) != null) { + if (result.compareAndSet(null, u)) + quietlyCompleteRoot(); + break; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class ReduceKeysTask + extends BulkTask { + final BiFunction reducer; + K result; + ReduceKeysTask rights, nextRight; + ReduceKeysTask + (BulkTask p, int b, int i, int f, Node[] t, + ReduceKeysTask nextRight, + BiFunction reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.reducer = reducer; + } + public final K getRawResult() { return result; } + public final void compute() { + final BiFunction reducer; + if ((reducer = this.reducer) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new ReduceKeysTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, reducer)).fork(); + } + K r = null; + for (Node p; (p = advance()) != null; ) { + K u = p.key; + r = (r == null) ? u : u == null ? r : reducer.apply(r, u); + } + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + ReduceKeysTask + t = (ReduceKeysTask)c, + s = t.rights; + while (s != null) { + K tr, sr; + if ((sr = s.result) != null) + t.result = (((tr = t.result) == null) ? sr : + reducer.apply(tr, sr)); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class ReduceValuesTask + extends BulkTask { + final BiFunction reducer; + V result; + ReduceValuesTask rights, nextRight; + ReduceValuesTask + (BulkTask p, int b, int i, int f, Node[] t, + ReduceValuesTask nextRight, + BiFunction reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.reducer = reducer; + } + public final V getRawResult() { return result; } + public final void compute() { + final BiFunction reducer; + if ((reducer = this.reducer) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new ReduceValuesTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, reducer)).fork(); + } + V r = null; + for (Node p; (p = advance()) != null; ) { + V v = p.val; + r = (r == null) ? v : reducer.apply(r, v); + } + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + ReduceValuesTask + t = (ReduceValuesTask)c, + s = t.rights; + while (s != null) { + V tr, sr; + if ((sr = s.result) != null) + t.result = (((tr = t.result) == null) ? sr : + reducer.apply(tr, sr)); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class ReduceEntriesTask + extends BulkTask> { + final BiFunction, Map.Entry, ? extends Map.Entry> reducer; + Map.Entry result; + ReduceEntriesTask rights, nextRight; + ReduceEntriesTask + (BulkTask p, int b, int i, int f, Node[] t, + ReduceEntriesTask nextRight, + BiFunction, Map.Entry, ? extends Map.Entry> reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.reducer = reducer; + } + public final Map.Entry getRawResult() { return result; } + public final void compute() { + final BiFunction, Map.Entry, ? extends Map.Entry> reducer; + if ((reducer = this.reducer) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new ReduceEntriesTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, reducer)).fork(); + } + Map.Entry r = null; + for (Node p; (p = advance()) != null; ) + r = (r == null) ? p : reducer.apply(r, p); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + ReduceEntriesTask + t = (ReduceEntriesTask)c, + s = t.rights; + while (s != null) { + Map.Entry tr, sr; + if ((sr = s.result) != null) + t.result = (((tr = t.result) == null) ? sr : + reducer.apply(tr, sr)); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceKeysTask + extends BulkTask { + final Function transformer; + final BiFunction reducer; + U result; + MapReduceKeysTask rights, nextRight; + MapReduceKeysTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceKeysTask nextRight, + Function transformer, + BiFunction reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.reducer = reducer; + } + public final U getRawResult() { return result; } + public final void compute() { + final Function transformer; + final BiFunction reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceKeysTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, reducer)).fork(); + } + U r = null; + for (Node p; (p = advance()) != null; ) { + U u; + if ((u = transformer.apply(p.key)) != null) + r = (r == null) ? u : reducer.apply(r, u); + } + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceKeysTask + t = (MapReduceKeysTask)c, + s = t.rights; + while (s != null) { + U tr, sr; + if ((sr = s.result) != null) + t.result = (((tr = t.result) == null) ? sr : + reducer.apply(tr, sr)); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceValuesTask + extends BulkTask { + final Function transformer; + final BiFunction reducer; + U result; + MapReduceValuesTask rights, nextRight; + MapReduceValuesTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceValuesTask nextRight, + Function transformer, + BiFunction reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.reducer = reducer; + } + public final U getRawResult() { return result; } + public final void compute() { + final Function transformer; + final BiFunction reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceValuesTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, reducer)).fork(); + } + U r = null; + for (Node p; (p = advance()) != null; ) { + U u; + if ((u = transformer.apply(p.val)) != null) + r = (r == null) ? u : reducer.apply(r, u); + } + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceValuesTask + t = (MapReduceValuesTask)c, + s = t.rights; + while (s != null) { + U tr, sr; + if ((sr = s.result) != null) + t.result = (((tr = t.result) == null) ? sr : + reducer.apply(tr, sr)); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceEntriesTask + extends BulkTask { + final Function, ? extends U> transformer; + final BiFunction reducer; + U result; + MapReduceEntriesTask rights, nextRight; + MapReduceEntriesTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceEntriesTask nextRight, + Function, ? extends U> transformer, + BiFunction reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.reducer = reducer; + } + public final U getRawResult() { return result; } + public final void compute() { + final Function, ? extends U> transformer; + final BiFunction reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceEntriesTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, reducer)).fork(); + } + U r = null; + for (Node p; (p = advance()) != null; ) { + U u; + if ((u = transformer.apply(p)) != null) + r = (r == null) ? u : reducer.apply(r, u); + } + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceEntriesTask + t = (MapReduceEntriesTask)c, + s = t.rights; + while (s != null) { + U tr, sr; + if ((sr = s.result) != null) + t.result = (((tr = t.result) == null) ? sr : + reducer.apply(tr, sr)); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceMappingsTask + extends BulkTask { + final BiFunction transformer; + final BiFunction reducer; + U result; + MapReduceMappingsTask rights, nextRight; + MapReduceMappingsTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceMappingsTask nextRight, + BiFunction transformer, + BiFunction reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.reducer = reducer; + } + public final U getRawResult() { return result; } + public final void compute() { + final BiFunction transformer; + final BiFunction reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceMappingsTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, reducer)).fork(); + } + U r = null; + for (Node p; (p = advance()) != null; ) { + U u; + if ((u = transformer.apply(p.key, p.val)) != null) + r = (r == null) ? u : reducer.apply(r, u); + } + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceMappingsTask + t = (MapReduceMappingsTask)c, + s = t.rights; + while (s != null) { + U tr, sr; + if ((sr = s.result) != null) + t.result = (((tr = t.result) == null) ? sr : + reducer.apply(tr, sr)); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceKeysToDoubleTask + extends BulkTask { + final ToDoubleFunction transformer; + final DoubleBinaryOperator reducer; + final double basis; + double result; + MapReduceKeysToDoubleTask rights, nextRight; + MapReduceKeysToDoubleTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceKeysToDoubleTask nextRight, + ToDoubleFunction transformer, + double basis, + DoubleBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Double getRawResult() { return result; } + public final void compute() { + final ToDoubleFunction transformer; + final DoubleBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + double r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceKeysToDoubleTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceKeysToDoubleTask + t = (MapReduceKeysToDoubleTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsDouble(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceValuesToDoubleTask + extends BulkTask { + final ToDoubleFunction transformer; + final DoubleBinaryOperator reducer; + final double basis; + double result; + MapReduceValuesToDoubleTask rights, nextRight; + MapReduceValuesToDoubleTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceValuesToDoubleTask nextRight, + ToDoubleFunction transformer, + double basis, + DoubleBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Double getRawResult() { return result; } + public final void compute() { + final ToDoubleFunction transformer; + final DoubleBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + double r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceValuesToDoubleTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.val)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceValuesToDoubleTask + t = (MapReduceValuesToDoubleTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsDouble(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceEntriesToDoubleTask + extends BulkTask { + final ToDoubleFunction> transformer; + final DoubleBinaryOperator reducer; + final double basis; + double result; + MapReduceEntriesToDoubleTask rights, nextRight; + MapReduceEntriesToDoubleTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceEntriesToDoubleTask nextRight, + ToDoubleFunction> transformer, + double basis, + DoubleBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Double getRawResult() { return result; } + public final void compute() { + final ToDoubleFunction> transformer; + final DoubleBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + double r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceEntriesToDoubleTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsDouble(r, transformer.applyAsDouble(p)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceEntriesToDoubleTask + t = (MapReduceEntriesToDoubleTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsDouble(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceMappingsToDoubleTask + extends BulkTask { + final ToDoubleBiFunction transformer; + final DoubleBinaryOperator reducer; + final double basis; + double result; + MapReduceMappingsToDoubleTask rights, nextRight; + MapReduceMappingsToDoubleTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceMappingsToDoubleTask nextRight, + ToDoubleBiFunction transformer, + double basis, + DoubleBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Double getRawResult() { return result; } + public final void compute() { + final ToDoubleBiFunction transformer; + final DoubleBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + double r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceMappingsToDoubleTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceMappingsToDoubleTask + t = (MapReduceMappingsToDoubleTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsDouble(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceKeysToLongTask + extends BulkTask { + final ToLongFunction transformer; + final LongBinaryOperator reducer; + final long basis; + long result; + MapReduceKeysToLongTask rights, nextRight; + MapReduceKeysToLongTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceKeysToLongTask nextRight, + ToLongFunction transformer, + long basis, + LongBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Long getRawResult() { return result; } + public final void compute() { + final ToLongFunction transformer; + final LongBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + long r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceKeysToLongTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsLong(r, transformer.applyAsLong(p.key)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceKeysToLongTask + t = (MapReduceKeysToLongTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsLong(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceValuesToLongTask + extends BulkTask { + final ToLongFunction transformer; + final LongBinaryOperator reducer; + final long basis; + long result; + MapReduceValuesToLongTask rights, nextRight; + MapReduceValuesToLongTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceValuesToLongTask nextRight, + ToLongFunction transformer, + long basis, + LongBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Long getRawResult() { return result; } + public final void compute() { + final ToLongFunction transformer; + final LongBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + long r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceValuesToLongTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsLong(r, transformer.applyAsLong(p.val)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceValuesToLongTask + t = (MapReduceValuesToLongTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsLong(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceEntriesToLongTask + extends BulkTask { + final ToLongFunction> transformer; + final LongBinaryOperator reducer; + final long basis; + long result; + MapReduceEntriesToLongTask rights, nextRight; + MapReduceEntriesToLongTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceEntriesToLongTask nextRight, + ToLongFunction> transformer, + long basis, + LongBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Long getRawResult() { return result; } + public final void compute() { + final ToLongFunction> transformer; + final LongBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + long r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceEntriesToLongTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsLong(r, transformer.applyAsLong(p)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceEntriesToLongTask + t = (MapReduceEntriesToLongTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsLong(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceMappingsToLongTask + extends BulkTask { + final ToLongBiFunction transformer; + final LongBinaryOperator reducer; + final long basis; + long result; + MapReduceMappingsToLongTask rights, nextRight; + MapReduceMappingsToLongTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceMappingsToLongTask nextRight, + ToLongBiFunction transformer, + long basis, + LongBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Long getRawResult() { return result; } + public final void compute() { + final ToLongBiFunction transformer; + final LongBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + long r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceMappingsToLongTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceMappingsToLongTask + t = (MapReduceMappingsToLongTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsLong(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceKeysToIntTask + extends BulkTask { + final ToIntFunction transformer; + final IntBinaryOperator reducer; + final int basis; + int result; + MapReduceKeysToIntTask rights, nextRight; + MapReduceKeysToIntTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceKeysToIntTask nextRight, + ToIntFunction transformer, + int basis, + IntBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Integer getRawResult() { return result; } + public final void compute() { + final ToIntFunction transformer; + final IntBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + int r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceKeysToIntTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsInt(r, transformer.applyAsInt(p.key)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceKeysToIntTask + t = (MapReduceKeysToIntTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsInt(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceValuesToIntTask + extends BulkTask { + final ToIntFunction transformer; + final IntBinaryOperator reducer; + final int basis; + int result; + MapReduceValuesToIntTask rights, nextRight; + MapReduceValuesToIntTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceValuesToIntTask nextRight, + ToIntFunction transformer, + int basis, + IntBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Integer getRawResult() { return result; } + public final void compute() { + final ToIntFunction transformer; + final IntBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + int r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceValuesToIntTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsInt(r, transformer.applyAsInt(p.val)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceValuesToIntTask + t = (MapReduceValuesToIntTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsInt(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceEntriesToIntTask + extends BulkTask { + final ToIntFunction> transformer; + final IntBinaryOperator reducer; + final int basis; + int result; + MapReduceEntriesToIntTask rights, nextRight; + MapReduceEntriesToIntTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceEntriesToIntTask nextRight, + ToIntFunction> transformer, + int basis, + IntBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Integer getRawResult() { return result; } + public final void compute() { + final ToIntFunction> transformer; + final IntBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + int r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceEntriesToIntTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsInt(r, transformer.applyAsInt(p)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceEntriesToIntTask + t = (MapReduceEntriesToIntTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsInt(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + @SuppressWarnings("serial") + static final class MapReduceMappingsToIntTask + extends BulkTask { + final ToIntBiFunction transformer; + final IntBinaryOperator reducer; + final int basis; + int result; + MapReduceMappingsToIntTask rights, nextRight; + MapReduceMappingsToIntTask + (BulkTask p, int b, int i, int f, Node[] t, + MapReduceMappingsToIntTask nextRight, + ToIntBiFunction transformer, + int basis, + IntBinaryOperator reducer) { + super(p, b, i, f, t); this.nextRight = nextRight; + this.transformer = transformer; + this.basis = basis; this.reducer = reducer; + } + public final Integer getRawResult() { return result; } + public final void compute() { + final ToIntBiFunction transformer; + final IntBinaryOperator reducer; + if ((transformer = this.transformer) != null && + (reducer = this.reducer) != null) { + int r = this.basis; + for (int i = baseIndex, f, h; batch > 0 && + (h = ((f = baseLimit) + i) >>> 1) > i;) { + addToPendingCount(1); + (rights = new MapReduceMappingsToIntTask + (this, batch >>>= 1, baseLimit = h, f, tab, + rights, transformer, r, reducer)).fork(); + } + for (Node p; (p = advance()) != null; ) + r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val)); + result = r; + CountedCompleter c; + for (c = firstComplete(); c != null; c = c.nextComplete()) { + @SuppressWarnings("unchecked") + MapReduceMappingsToIntTask + t = (MapReduceMappingsToIntTask)c, + s = t.rights; + while (s != null) { + t.result = reducer.applyAsInt(t.result, s.result); + s = t.rights = s.nextRight; + } + } + } + } + } + + // Unsafe mechanics + private static final sun.misc.Unsafe U; + private static final long SIZECTL; + private static final long TRANSFERINDEX; + private static final long BASECOUNT; + private static final long CELLSBUSY; + private static final long CELLVALUE; + private static final long ABASE; + private static final int ASHIFT; + + static { + try { + U = sun.misc.Unsafe.getUnsafe(); + Class k = ConcurrentHashMap.class; + SIZECTL = U.objectFieldOffset + (k.getDeclaredField("sizeCtl")); + TRANSFERINDEX = U.objectFieldOffset + (k.getDeclaredField("transferIndex")); + BASECOUNT = U.objectFieldOffset + (k.getDeclaredField("baseCount")); + CELLSBUSY = U.objectFieldOffset + (k.getDeclaredField("cellsBusy")); + Class ck = CounterCell.class; + CELLVALUE = U.objectFieldOffset + (ck.getDeclaredField("value")); + Class ak = Node[].class; + ABASE = U.arrayBaseOffset(ak); + int scale = U.arrayIndexScale(ak); + if ((scale & (scale - 1)) != 0) + throw new Error("data type scale not a power of two"); + ASHIFT = 31 - Integer.numberOfLeadingZeros(scale); + } catch (Exception e) { + throw new Error(e); + } + } +} + + + diff --git a/week_04/17/ConcurrentLinkedQueue b/week_04/17/ConcurrentLinkedQueue new file mode 100644 index 0000000..4ed65a1 --- /dev/null +++ b/week_04/17/ConcurrentLinkedQueue @@ -0,0 +1,164 @@ +##ConcurrentLinkedQueue--多线程链表队列 + 1.AbstractQueue + boolean add(E e); + remove(); + element() ; + clear(); + addAll(Collection c) + + + 2.实现Queue + add(e); + offer(E e); + E remove(); + E poll(); + E element(); + E peek(); +##属性 + 1.内部类Node + 2.head + 3.tail +##构造方法 + //空的node + public ConcurrentLinkedQueue() { + head = tail = new Node(null); + } + //把数据放到队列中--屁股后面依次放着走 + public ConcurrentLinkedQueue(Collection c) { + Node h = null, t = null; + for (E e : c) { + //元素不为空 + checkNotNull(e); + + Node newNode = new Node(e); + //空队列 + if (h == null) + //就头尾都是这个 + h = t = newNode; + else { + //如果已经有了头,就在后面跟着放数据 + t.lazySetNext(newNode); + t = newNode; + } + } + //如果都遍历完了,头是空的,把这个队列变成空的 + if (h == null) + h = t = new Node(null); + head = h; + tail = t; + } +##入队/出队方法 + ##入队 + + public boolean add(E e) { + return offer(e); + } + + public boolean offer(E e) { + //空值检测 + checkNotNull(e); + final Node newNode = new Node(e); + + for (Node t = tail, p = t;;) { + //从尾开始 + Node q = p.next; + //如果下个节点是空的 + if (q == null) { + // p is last node + //直接把内存地址上的值改成新值 + if (p.casNext(null, newNode)) { + // Successful CAS is the linearization point + // for e to become an element of this queue, + // and for newNode to become "live". + //如果不是尾节点,就把尾节点的值改成新值 + if (p != t) // hop two nodes at a time + + casTail(t, newNode); // Failure is OK. + return true; + } + // Lost CAS race to another thread; re-read next + } + + //p的下一个节点等于p的话,就代表着P这个节点已经被删除了(已经出队列了) + else if (p == q) + // We have fallen off list. If tail is unchanged, it + // will also be off-list, in which case we need to + // jump to head, from which all live nodes are always + // reachable. Else the new tail is a better bet. + //我们就需要重新设置P的值 + p = (t != (t = tail)) ? t : head; + else + //尾部后面还有值的话,就需要重新把之前的尾部的值设置一下 + + // Check for tail updates after two hops. + p = (p != t && t != (t = tail)) ? t : q; + } + } + + ##出队 + public boolean remove(Object o) { + if (o != null) { + Node next, pred = null; + //从头开始 + for (Node p = first(); p != null; pred = p, p = next) { + boolean removed = false; + //获取这个元素 + E item = p.item; + + if (item != null) { + //如果这个元素不为空的话,就一直到把它删除为止 + if (!o.equals(item)) { + //不相等就一直找到相等为止 + next = succ(p); + continue; + } + //两个是一样的就直接把内存上的值改掉 + removed = p.casItem(item, null); + } + //如果这个元素是空的话,就获取下一个节点 + + next = succ(p); + //当前这个节点不为空,并且替换它的节点也不为空的话就替换掉 + if (pred != null && next != null) // unlink + pred.casNext(p, next); + if (removed) + return true; + } + } + return false; + } + + + public E poll() { + restartFromHead: + for (;;) { + for (Node h = head, p = h, q;;) { + //取出头节点的数据 + E item = p.item; + //如果数据不为空就设置为空 + if (item != null && p.casItem(item, null)) { + // Successful CAS is the linearization point + // for item to be removed from this queue. + //如果不相等(有被改动了),更新头节点 + if (p != h) // hop two nodes at a time + updateHead(h, ((q = p.next) != null) ? q : p); + return item; + } + //下一个节点是空的话 + else if ((q = p.next) == null) { + //更新头节点为空 + updateHead(h, p); + return null; + } + //标记重新来 + else if (p == q) + continue restartFromHead; + else + p = q; + } + } + } + + ##peek + peek---获取队列头的元素 + \ No newline at end of file diff --git a/week_04/17/CopyOnWriteArrayList b/week_04/17/CopyOnWriteArrayList new file mode 100644 index 0000000..4c4df7a --- /dev/null +++ b/week_04/17/CopyOnWriteArrayList @@ -0,0 +1,1355 @@ +##CopyOnWriteArrayList----多线程集合(保证在多线程下ArrayList的数据安全) + 1.接口实现: + List, 有List的所有方法。 + RandomAccess, 可快速访问,一次出结果 + Cloneable, 可拷贝 + java.io.Serializable 可序列化 + 1.实现原理,每一次修改会重新开辟一个空间(新的数组),做修改/增加/删除操作,然后再将地址引用到新的集合地址。 + //TODO + 这样的话,如果在修改的途中有线程在访问的时候,会访问老的数据,但是增删改操作就会排队。 + + 缺点: 1、耗内存(集合复制) + 2、实时性不高 + 优点:多线程下 数据一致性。 + + 所以场景:集合数据不大 + 读多写少的情况(每一次写都会去复制数组,消耗大) + 实时性要求不高(因为,修改数据的过程中,还没有切换内存地址,所以会读取到之前的数据) + + +##源码分析 + + { + private static final long serialVersionUID = 8673264195747942595L; + + //实例一个锁(可重入锁默认非公平锁) + final transient ReentrantLock lock = new ReentrantLock(); + + //一个可见性的对象数组,仅仅只能通过getArry/setArray进行操作 + private transient volatile Object[] array; + + //获取数组 + final Object[] getArray() { + return array; + } + //设置数组 + final void setArray(Object[] a) { + array = a; + } + + //构造一个空数组 + public CopyOnWriteArrayList() { + setArray(new Object[0]); + } + + //构造方法(集合) + public CopyOnWriteArrayList(Collection c) { + Object[] elements; + if (c.getClass() == CopyOnWriteArrayList.class) + elements = ((CopyOnWriteArrayList)c).getArray(); + else { + elements = c.toArray(); + // c.toArray might (incorrectly) not return Object[] (see 6260652) + if (elements.getClass() != Object[].class) + elements = Arrays.copyOf(elements, elements.length, Object[].class); + } + //只能通过setArray 方法操作这个数组 + setArray(elements); + } + + //构造方法(数组) + public CopyOnWriteArrayList(E[] toCopyIn) { + setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class)); + } + + + public int size() { + return getArray().length; + } + + + public boolean isEmpty() { + return size() == 0; + } + + + private static boolean eq(Object o1, Object o2) { + return (o1 == null) ? o2 == null : o1.equals(o2); + } + + + private static int indexOf(Object o, Object[] elements, + int index, int fence) { + if (o == null) { + for (int i = index; i < fence; i++) + if (elements[i] == null) + return i; + } else { + for (int i = index; i < fence; i++) + if (o.equals(elements[i])) + return i; + } + return -1; + } + + + private static int lastIndexOf(Object o, Object[] elements, int index) { + if (o == null) { + for (int i = index; i >= 0; i--) + if (elements[i] == null) + return i; + } else { + for (int i = index; i >= 0; i--) + if (o.equals(elements[i])) + return i; + } + return -1; + } + + + public boolean contains(Object o) { + Object[] elements = getArray(); + return indexOf(o, elements, 0, elements.length) >= 0; + } + + + public int indexOf(Object o) { + Object[] elements = getArray(); + return indexOf(o, elements, 0, elements.length); + } + + //从index开始向后找 + public int indexOf(E e, int index) { + Object[] elements = getArray(); + return indexOf(e, elements, index, elements.length); + } + + /** + * {@inheritDoc} + */ + public int lastIndexOf(Object o) { + Object[] elements = getArray(); + return lastIndexOf(o, elements, elements.length - 1); + } + + //从index向前找E + public int lastIndexOf(E e, int index) { + Object[] elements = getArray(); + return lastIndexOf(e, elements, index); + } + + /** + * Returns a shallow copy of this list. (The elements themselves + * are not copied.) + * + * @return a clone of this list + */ + public Object clone() { + try { + @SuppressWarnings("unchecked") + CopyOnWriteArrayList clone = + (CopyOnWriteArrayList) super.clone(); + clone.resetLock(); + return clone; + } catch (CloneNotSupportedException e) { + // this shouldn't happen, since we are Cloneable + throw new InternalError(); + } + } + + /** + * Returns an array containing all of the elements in this list + * in proper sequence (from first to last element). + * + *

The returned array will be "safe" in that no references to it are + * maintained by this list. (In other words, this method must allocate + * a new array). The caller is thus free to modify the returned array. + * + *

This method acts as bridge between array-based and collection-based + * APIs. + * + * @return an array containing all the elements in this list + */ + public Object[] toArray() { + Object[] elements = getArray(); + return Arrays.copyOf(elements, elements.length); + } + + /** + * Returns an array containing all of the elements in this list in + * proper sequence (from first to last element); the runtime type of + * the returned array is that of the specified array. If the list fits + * in the specified array, it is returned therein. Otherwise, a new + * array is allocated with the runtime type of the specified array and + * the size of this list. + * + *

If this list fits in the specified array with room to spare + * (i.e., the array has more elements than this list), the element in + * the array immediately following the end of the list is set to + * {@code null}. (This is useful in determining the length of this + * list only if the caller knows that this list does not contain + * any null elements.) + * + *

Like the {@link #toArray()} method, this method acts as bridge between + * array-based and collection-based APIs. Further, this method allows + * precise control over the runtime type of the output array, and may, + * under certain circumstances, be used to save allocation costs. + * + *

Suppose {@code x} is a list known to contain only strings. + * The following code can be used to dump the list into a newly + * allocated array of {@code String}: + * + *

 {@code String[] y = x.toArray(new String[0]);}
+ * + * Note that {@code toArray(new Object[0])} is identical in function to + * {@code toArray()}. + * + * @param a the array into which the elements of the list are to + * be stored, if it is big enough; otherwise, a new array of the + * same runtime type is allocated for this purpose. + * @return an array containing all the elements in this list + * @throws ArrayStoreException if the runtime type of the specified array + * is not a supertype of the runtime type of every element in + * this list + * @throws NullPointerException if the specified array is null + */ + @SuppressWarnings("unchecked") + public T[] toArray(T a[]) { + Object[] elements = getArray(); + int len = elements.length; + if (a.length < len) + return (T[]) Arrays.copyOf(elements, len, a.getClass()); + else { + System.arraycopy(elements, 0, a, 0, len); + if (a.length > len) + a[len] = null; + return a; + } + } + + // Positional Access Operations + + //获取指定数组中的某一角标的值 + @SuppressWarnings("unchecked") + private E get(Object[] a, int index) { + return (E) a[index]; + } + + //获取新改动数组中某一个值 + public E get(int index) { + return get(getArray(), index); + } + + //指定角标设置指定元素,返回老值 + public E set(int index, E element) { + final ReentrantLock lock = this.lock; + //上锁 + lock.lock(); + + try { + //拿到数组(其他线程都进不来) + Object[] elements = getArray(); + //获取角标对应的数据 + E oldValue = get(elements, index); + //如果和角标的值不相等 + if (oldValue != element) { + //原始数据的长度 + int len = elements.length; + Object[] newElements = Arrays.copyOf(elements, len); + newElements[index] = element; + setArray(newElements); + } else { + // Not quite a no-op; ensures volatile write semantics + setArray(elements); + } + return oldValue; + } finally { + lock.unlock(); + } + } + + //添加元素--加在末尾 + public boolean add(E e) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + //新长度数组 + Object[] newElements = Arrays.copyOf(elements, len + 1); + //最后一个地方加元素 + newElements[len] = e; + setArray(newElements); + return true; + } finally { + lock.unlock(); + } + } + + //集合中 固定角标添加元素 + public void add(int index, E element) { + //锁 + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + if (index > len || index < 0) + throw new IndexOutOfBoundsException("Index: "+index+ + ", Size: "+len); + + //定义新数组 + Object[] newElements; + //需要移动的位置 + int numMoved = len - index; + if (numMoved == 0) + //末尾添加则直接copy到新数组 + newElements = Arrays.copyOf(elements, len + 1); + else { + //中间位置 + //新建一个长度+1的数组 + newElements = new Object[len + 1]; + System.arraycopy(elements, 0, newElements, 0, index); + System.arraycopy(elements, index, newElements, index + 1, + numMoved); + } + newElements[index] = element; + setArray(newElements); + } finally { + lock.unlock(); + } + } + + /** + * Removes the element at the specified position in this list. + * Shifts any subsequent elements to the left (subtracts one from their + * indices). Returns the element that was removed from the list. + * + * @throws IndexOutOfBoundsException {@inheritDoc} + */ + public E remove(int index) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + E oldValue = get(elements, index); + int numMoved = len - index - 1; + //末尾删除 + if (numMoved == 0) + setArray(Arrays.copyOf(elements, len - 1)); + else { + Object[] newElements = new Object[len - 1]; + //把前半部分拷进数组 + System.arraycopy(elements, 0, newElements, 0, index); + //再把后半部分拷进数组 + System.arraycopy(elements, index + 1, newElements, index, + numMoved); + setArray(newElements); + } + return oldValue; + } finally { + lock.unlock(); + } + } + + + public boolean remove(Object o) { + Object[] snapshot = getArray(); + //从数组中找到他的角标 + int index = indexOf(o, snapshot, 0, snapshot.length); + //移除 + return (index < 0) ? false : remove(o, snapshot, index); + } + + /** + * A version of remove(Object) using the strong hint that given + * recent snapshot contains o at the given index. + */ + private boolean remove(Object o, Object[] snapshot, int index) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] current = getArray(); + //拿到当前数组长度 + int len = current.length; + //如果新数组和现在内存的数组不一样,则需要去找到要找的角标 + + if (snapshot != current) + + findIndex-----打了个标签,{}这里面的代码都属于它的 + findIndex: { + //获取一个那个最小 + int prefix = Math.min(index, len); + for (int i = 0; i < prefix; i++) { + if (current[i] != snapshot[i] && eq(o, current[i])) { + index = i; + //直接跳出findIndex代码块 + break findIndex; + } + } + if (index >= len) + return false; + if (current[index] == o) + break findIndex; + index = indexOf(o, current, index, len); + if (index < 0) + return false; + } + + //开始拷贝数据 + Object[] newElements = new Object[len - 1]; + //拷贝原来数组index前半段数据到新数组中 + System.arraycopy(current, 0, newElements, 0, index); + //拷贝原来数组index之后的数据到新新数组中 + System.arraycopy(current, index + 1, + newElements, index, + len - index - 1); + setArray(newElements); + return true; + } finally { + lock.unlock(); + } + } + + //范围删除 + void removeRange(int fromIndex, int toIndex) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + + if (fromIndex < 0 || toIndex > len || toIndex < fromIndex) + throw new IndexOutOfBoundsException(); + int newlen = len - (toIndex - fromIndex); + int numMoved = len - toIndex; + if (numMoved == 0) + setArray(Arrays.copyOf(elements, newlen)); + else { + Object[] newElements = new Object[newlen]; + System.arraycopy(elements, 0, newElements, 0, fromIndex); + System.arraycopy(elements, toIndex, newElements, + fromIndex, numMoved); + setArray(newElements); + } + } finally { + lock.unlock(); + } + } + + /** + * Appends the element, if not present. + * + * @param e element to be added to this list, if absent + * @return {@code true} if the element was added + */ + public boolean addIfAbsent(E e) { + Object[] snapshot = getArray(); + return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false : + addIfAbsent(e, snapshot); + } + + //添加一个元素到数组中,如果这个元素不存在的话。 + private boolean addIfAbsent(E e, Object[] snapshot) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + //当前数组 + Object[] current = getArray(); + int len = current.length; + //之前的快照数组和现在的数组不一样 + if (snapshot != current) { + // Optimize for lost race to another addXXX operation + //找到比较小的长度 + int common = Math.min(snapshot.length, len); + + for (int i = 0; i < common; i++) + //快照中不存在,但是存在与当前数组中 + if (current[i] != snapshot[i] && eq(e, current[i])) + return false; + if (indexOf(e, current, common, len) >= 0) + return false; + } + //当前数组中 不存在, 那就添加进去,返回成功 + Object[] newElements = Arrays.copyOf(current, len + 1); + newElements[len] = e; + setArray(newElements); + return true; + } finally { + lock.unlock(); + } + } + + + public boolean containsAll(Collection c) { + Object[] elements = getArray(); + int len = elements.length; + for (Object e : c) { + if (indexOf(e, elements, 0, len) < 0) + return false; + } + return true; + } + + //删除该集合 + public boolean removeAll(Collection c) { + if (c == null) throw new NullPointerException(); + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + if (len != 0) { + // temp array holds those elements we know we want to keep + int newlen = 0; + //搞一个空数组等待 + Object[] temp = new Object[len]; + + //遍历当前集合 + for (int i = 0; i < len; ++i) { + Object element = elements[i]; + //待删数组不含有这个数据,就把这个数据存起来~ + if (!c.contains(element)) + temp[newlen++] = element; + } + //新数组放进去 + if (newlen != len) { + setArray(Arrays.copyOf(temp, newlen)); + return true; + } + } + return false; + } finally { + lock.unlock(); + } + } + + //保留这个集合的数据,其他的数据剔除 + public boolean retainAll(Collection c) { + if (c == null) throw new NullPointerException(); + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + if (len != 0) { + // temp array holds those elements we know we want to keep + int newlen = 0; + Object[] temp = new Object[len]; + for (int i = 0; i < len; ++i) { + Object element = elements[i]; + if (c.contains(element)) + temp[newlen++] = element; + } + if (newlen != len) { + setArray(Arrays.copyOf(temp, newlen)); + return true; + } + } + return false; + } finally { + lock.unlock(); + } + } + + //把新集合放在老集合的屁股后面,返回新集合的长度 + public int addAllAbsent(Collection c) { + Object[] cs = c.toArray(); + if (cs.length == 0) + return 0; + final ReentrantLock lock = this.lock; + lock.lock(); + try { + //当前数组长度 + Object[] elements = getArray(); + int len = elements.length; + + int added = 0; + // uniquify and compact elements in cs + for (int i = 0; i < cs.length; ++i) { + Object e = cs[i]; + //在当前数组的一段中没有,参数集合中从头开始 也没有,就把这个从头放着走 + if (indexOf(e, elements, 0, len) < 0 && + indexOf(e, cs, 0, added) < 0) + cs[added++] = e; + } + if (added > 0) { + Object[] newElements = Arrays.copyOf(elements, len + added); + System.arraycopy(cs, 0, newElements, len, added); + setArray(newElements); + } + return added; + } finally { + lock.unlock(); + } + } + + + public void clear() { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + setArray(new Object[0]); + } finally { + lock.unlock(); + } + } + + + public boolean addAll(Collection c) { + Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ? + ((CopyOnWriteArrayList)c).getArray() : c.toArray(); + if (cs.length == 0) + return false; + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + if (len == 0 && cs.getClass() == Object[].class) + setArray(cs); + else { + Object[] newElements = Arrays.copyOf(elements, len + cs.length); + System.arraycopy(cs, 0, newElements, len, cs.length); + setArray(newElements); + } + return true; + } finally { + lock.unlock(); + } + } + + + public boolean addAll(int index, Collection c) { + Object[] cs = c.toArray(); + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + if (index > len || index < 0) + throw new IndexOutOfBoundsException("Index: "+index+ + ", Size: "+len); + if (cs.length == 0) + return false; + int numMoved = len - index; + Object[] newElements; + if (numMoved == 0) + newElements = Arrays.copyOf(elements, len + cs.length); + else { + newElements = new Object[len + cs.length]; + System.arraycopy(elements, 0, newElements, 0, index); + System.arraycopy(elements, index, + newElements, index + cs.length, + numMoved); + } + System.arraycopy(cs, 0, newElements, index, cs.length); + setArray(newElements); + return true; + } finally { + lock.unlock(); + } + } + + public void forEach(Consumer action) { + if (action == null) throw new NullPointerException(); + Object[] elements = getArray(); + int len = elements.length; + for (int i = 0; i < len; ++i) { + @SuppressWarnings("unchecked") E e = (E) elements[i]; + action.accept(e); + } + } + + + //Predicate为java8的函数编程接口 断言。 类似判断 + //条件删除 + public boolean removeIf(Predicate filter) { + if (filter == null) throw new NullPointerException(); + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + if (len != 0) { + int newlen = 0; + Object[] temp = new Object[len]; + for (int i = 0; i < len; ++i) { + @SuppressWarnings("unchecked") E e = (E) elements[i]; + //符合你条件的---全部剔除 + if (!filter.test(e)) + temp[newlen++] = e; + } + if (newlen != len) { + setArray(Arrays.copyOf(temp, newlen)); + return true; + } + } + return false; + } finally { + lock.unlock(); + } + } + + public void replaceAll(UnaryOperator operator) { + if (operator == null) throw new NullPointerException(); + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + Object[] newElements = Arrays.copyOf(elements, len); + for (int i = 0; i < len; ++i) { + @SuppressWarnings("unchecked") E e = (E) elements[i]; + newElements[i] = operator.apply(e); + } + setArray(newElements); + } finally { + lock.unlock(); + } + } + + public void sort(Comparator c) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + Object[] newElements = Arrays.copyOf(elements, elements.length); + @SuppressWarnings("unchecked") E[] es = (E[])newElements; + Arrays.sort(es, c); + setArray(newElements); + } finally { + lock.unlock(); + } + } + + + private void writeObject(java.io.ObjectOutputStream s) + throws java.io.IOException { + + s.defaultWriteObject(); + + Object[] elements = getArray(); + // Write out array length + s.writeInt(elements.length); + + // Write out all elements in the proper order. + for (Object element : elements) + s.writeObject(element); + } + + + private void readObject(java.io.ObjectInputStream s) + throws java.io.IOException, ClassNotFoundException { + + s.defaultReadObject(); + + // bind to new lock + resetLock(); + + // Read in array length and allocate array + int len = s.readInt(); + SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, len); + Object[] elements = new Object[len]; + + // Read in all elements in the proper order. + for (int i = 0; i < len; i++) + elements[i] = s.readObject(); + setArray(elements); + } + + /** + * Returns a string representation of this list. The string + * representation consists of the string representations of the list's + * elements in the order they are returned by its iterator, enclosed in + * square brackets ({@code "[]"}). Adjacent elements are separated by + * the characters {@code ", "} (comma and space). Elements are + * converted to strings as by {@link String#valueOf(Object)}. + * + * @return a string representation of this list + */ + public String toString() { + return Arrays.toString(getArray()); + } + + + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof List)) + return false; + + List list = (List)(o); + Iterator it = list.iterator(); + Object[] elements = getArray(); + int len = elements.length; + for (int i = 0; i < len; ++i) + if (!it.hasNext() || !eq(elements[i], it.next())) + return false; + if (it.hasNext()) + return false; + return true; + } + + + public int hashCode() { + int hashCode = 1; + Object[] elements = getArray(); + int len = elements.length; + for (int i = 0; i < len; ++i) { + Object obj = elements[i]; + hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode()); + } + return hashCode; + } + + + //构造一个当前数组的迭代器 + public ListIterator listIterator(int index) { + Object[] elements = getArray(); + int len = elements.length; + if (index < 0 || index > len) + throw new IndexOutOfBoundsException("Index: "+index); + + return new COWIterator(elements, index); + } + + + public Spliterator spliterator() { + return Spliterators.spliterator + (getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED); + } + + static final class COWIterator implements ListIterator { + /** Snapshot of the array */ + private final Object[] snapshot; + /** Index of element to be returned by subsequent call to next. */ + private int cursor; + + private COWIterator(Object[] elements, int initialCursor) { + cursor = initialCursor; + snapshot = elements; + } + + public boolean hasNext() { + return cursor < snapshot.length; + } + + public boolean hasPrevious() { + return cursor > 0; + } + + @SuppressWarnings("unchecked") + public E next() { + if (! hasNext()) + throw new NoSuchElementException(); + return (E) snapshot[cursor++]; + } + + @SuppressWarnings("unchecked") + public E previous() { + if (! hasPrevious()) + throw new NoSuchElementException(); + return (E) snapshot[--cursor]; + } + + public int nextIndex() { + return cursor; + } + + public int previousIndex() { + return cursor-1; + } + + /** + * Not supported. Always throws UnsupportedOperationException. + * @throws UnsupportedOperationException always; {@code remove} + * is not supported by this iterator. + */ + public void remove() { + throw new UnsupportedOperationException(); + } + + /** + * Not supported. Always throws UnsupportedOperationException. + * @throws UnsupportedOperationException always; {@code set} + * is not supported by this iterator. + */ + public void set(E e) { + throw new UnsupportedOperationException(); + } + + /** + * Not supported. Always throws UnsupportedOperationException. + * @throws UnsupportedOperationException always; {@code add} + * is not supported by this iterator. + */ + public void add(E e) { + throw new UnsupportedOperationException(); + } + + @Override + public void forEachRemaining(Consumer action) { + Objects.requireNonNull(action); + Object[] elements = snapshot; + final int size = elements.length; + for (int i = cursor; i < size; i++) { + @SuppressWarnings("unchecked") E e = (E) elements[i]; + action.accept(e); + } + cursor = size; + } + } + + + public List subList(int fromIndex, int toIndex) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + Object[] elements = getArray(); + int len = elements.length; + if (fromIndex < 0 || toIndex > len || fromIndex > toIndex) + throw new IndexOutOfBoundsException(); + return new COWSubList(this, fromIndex, toIndex); + } finally { + lock.unlock(); + } + } + + + private static class COWSubList + extends AbstractList + implements RandomAccess + { + private final CopyOnWriteArrayList l; + private final int offset; + private int size; + private Object[] expectedArray; + + // only call this holding l's lock + COWSubList(CopyOnWriteArrayList list, + int fromIndex, int toIndex) { + l = list; + expectedArray = l.getArray(); + offset = fromIndex; + size = toIndex - fromIndex; + } + + // only call this holding l's lock + private void checkForComodification() { + if (l.getArray() != expectedArray) + throw new ConcurrentModificationException(); + } + + // only call this holding l's lock + private void rangeCheck(int index) { + if (index < 0 || index >= size) + throw new IndexOutOfBoundsException("Index: "+index+ + ",Size: "+size); + } + + public E set(int index, E element) { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + rangeCheck(index); + checkForComodification(); + E x = l.set(index+offset, element); + expectedArray = l.getArray(); + return x; + } finally { + lock.unlock(); + } + } + + public E get(int index) { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + rangeCheck(index); + checkForComodification(); + return l.get(index+offset); + } finally { + lock.unlock(); + } + } + + public int size() { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + checkForComodification(); + return size; + } finally { + lock.unlock(); + } + } + + public void add(int index, E element) { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + checkForComodification(); + if (index < 0 || index > size) + throw new IndexOutOfBoundsException(); + l.add(index+offset, element); + expectedArray = l.getArray(); + size++; + } finally { + lock.unlock(); + } + } + + public void clear() { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + checkForComodification(); + l.removeRange(offset, offset+size); + expectedArray = l.getArray(); + size = 0; + } finally { + lock.unlock(); + } + } + + public E remove(int index) { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + rangeCheck(index); + checkForComodification(); + E result = l.remove(index+offset); + expectedArray = l.getArray(); + size--; + return result; + } finally { + lock.unlock(); + } + } + + public boolean remove(Object o) { + int index = indexOf(o); + if (index == -1) + return false; + remove(index); + return true; + } + + public Iterator iterator() { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + checkForComodification(); + return new COWSubListIterator(l, 0, offset, size); + } finally { + lock.unlock(); + } + } + + public ListIterator listIterator(int index) { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + checkForComodification(); + if (index < 0 || index > size) + throw new IndexOutOfBoundsException("Index: "+index+ + ", Size: "+size); + return new COWSubListIterator(l, index, offset, size); + } finally { + lock.unlock(); + } + } + + public List subList(int fromIndex, int toIndex) { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + checkForComodification(); + if (fromIndex < 0 || toIndex > size || fromIndex > toIndex) + throw new IndexOutOfBoundsException(); + return new COWSubList(l, fromIndex + offset, + toIndex + offset); + } finally { + lock.unlock(); + } + } + + public void forEach(Consumer action) { + if (action == null) throw new NullPointerException(); + int lo = offset; + int hi = offset + size; + Object[] a = expectedArray; + if (l.getArray() != a) + throw new ConcurrentModificationException(); + if (lo < 0 || hi > a.length) + throw new IndexOutOfBoundsException(); + for (int i = lo; i < hi; ++i) { + @SuppressWarnings("unchecked") E e = (E) a[i]; + action.accept(e); + } + } + + public void replaceAll(UnaryOperator operator) { + if (operator == null) throw new NullPointerException(); + final ReentrantLock lock = l.lock; + lock.lock(); + try { + int lo = offset; + int hi = offset + size; + Object[] elements = expectedArray; + if (l.getArray() != elements) + throw new ConcurrentModificationException(); + int len = elements.length; + if (lo < 0 || hi > len) + throw new IndexOutOfBoundsException(); + Object[] newElements = Arrays.copyOf(elements, len); + for (int i = lo; i < hi; ++i) { + @SuppressWarnings("unchecked") E e = (E) elements[i]; + newElements[i] = operator.apply(e); + } + l.setArray(expectedArray = newElements); + } finally { + lock.unlock(); + } + } + + public void sort(Comparator c) { + final ReentrantLock lock = l.lock; + lock.lock(); + try { + int lo = offset; + int hi = offset + size; + Object[] elements = expectedArray; + if (l.getArray() != elements) + throw new ConcurrentModificationException(); + int len = elements.length; + if (lo < 0 || hi > len) + throw new IndexOutOfBoundsException(); + Object[] newElements = Arrays.copyOf(elements, len); + @SuppressWarnings("unchecked") E[] es = (E[])newElements; + Arrays.sort(es, lo, hi, c); + l.setArray(expectedArray = newElements); + } finally { + lock.unlock(); + } + } + + public boolean removeAll(Collection c) { + if (c == null) throw new NullPointerException(); + boolean removed = false; + final ReentrantLock lock = l.lock; + lock.lock(); + try { + int n = size; + if (n > 0) { + int lo = offset; + int hi = offset + n; + Object[] elements = expectedArray; + if (l.getArray() != elements) + throw new ConcurrentModificationException(); + int len = elements.length; + if (lo < 0 || hi > len) + throw new IndexOutOfBoundsException(); + int newSize = 0; + Object[] temp = new Object[n]; + for (int i = lo; i < hi; ++i) { + Object element = elements[i]; + if (!c.contains(element)) + temp[newSize++] = element; + } + if (newSize != n) { + Object[] newElements = new Object[len - n + newSize]; + System.arraycopy(elements, 0, newElements, 0, lo); + System.arraycopy(temp, 0, newElements, lo, newSize); + System.arraycopy(elements, hi, newElements, + lo + newSize, len - hi); + size = newSize; + removed = true; + l.setArray(expectedArray = newElements); + } + } + } finally { + lock.unlock(); + } + return removed; + } + + public boolean retainAll(Collection c) { + if (c == null) throw new NullPointerException(); + boolean removed = false; + final ReentrantLock lock = l.lock; + lock.lock(); + try { + int n = size; + if (n > 0) { + int lo = offset; + int hi = offset + n; + Object[] elements = expectedArray; + if (l.getArray() != elements) + throw new ConcurrentModificationException(); + int len = elements.length; + if (lo < 0 || hi > len) + throw new IndexOutOfBoundsException(); + int newSize = 0; + Object[] temp = new Object[n]; + for (int i = lo; i < hi; ++i) { + Object element = elements[i]; + if (c.contains(element)) + temp[newSize++] = element; + } + if (newSize != n) { + Object[] newElements = new Object[len - n + newSize]; + System.arraycopy(elements, 0, newElements, 0, lo); + System.arraycopy(temp, 0, newElements, lo, newSize); + System.arraycopy(elements, hi, newElements, + lo + newSize, len - hi); + size = newSize; + removed = true; + l.setArray(expectedArray = newElements); + } + } + } finally { + lock.unlock(); + } + return removed; + } + + public boolean removeIf(Predicate filter) { + if (filter == null) throw new NullPointerException(); + boolean removed = false; + final ReentrantLock lock = l.lock; + lock.lock(); + try { + int n = size; + if (n > 0) { + int lo = offset; + int hi = offset + n; + Object[] elements = expectedArray; + if (l.getArray() != elements) + throw new ConcurrentModificationException(); + int len = elements.length; + if (lo < 0 || hi > len) + throw new IndexOutOfBoundsException(); + int newSize = 0; + Object[] temp = new Object[n]; + for (int i = lo; i < hi; ++i) { + @SuppressWarnings("unchecked") E e = (E) elements[i]; + if (!filter.test(e)) + temp[newSize++] = e; + } + if (newSize != n) { + Object[] newElements = new Object[len - n + newSize]; + System.arraycopy(elements, 0, newElements, 0, lo); + System.arraycopy(temp, 0, newElements, lo, newSize); + System.arraycopy(elements, hi, newElements, + lo + newSize, len - hi); + size = newSize; + removed = true; + l.setArray(expectedArray = newElements); + } + } + } finally { + lock.unlock(); + } + return removed; + } + + public Spliterator spliterator() { + int lo = offset; + int hi = offset + size; + Object[] a = expectedArray; + if (l.getArray() != a) + throw new ConcurrentModificationException(); + if (lo < 0 || hi > a.length) + throw new IndexOutOfBoundsException(); + return Spliterators.spliterator + (a, lo, hi, Spliterator.IMMUTABLE | Spliterator.ORDERED); + } + + } + + private static class COWSubListIterator implements ListIterator { + private final ListIterator it; + private final int offset; + private final int size; + + COWSubListIterator(List l, int index, int offset, int size) { + this.offset = offset; + this.size = size; + it = l.listIterator(index+offset); + } + + public boolean hasNext() { + return nextIndex() < size; + } + + public E next() { + if (hasNext()) + return it.next(); + else + throw new NoSuchElementException(); + } + + public boolean hasPrevious() { + return previousIndex() >= 0; + } + + public E previous() { + if (hasPrevious()) + return it.previous(); + else + throw new NoSuchElementException(); + } + + public int nextIndex() { + return it.nextIndex() - offset; + } + + public int previousIndex() { + return it.previousIndex() - offset; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + public void set(E e) { + throw new UnsupportedOperationException(); + } + + public void add(E e) { + throw new UnsupportedOperationException(); + } + + @Override + public void forEachRemaining(Consumer action) { + Objects.requireNonNull(action); + int s = size; + ListIterator i = it; + while (nextIndex() < s) { + action.accept(i.next()); + } + } + } + + // Support for resetting lock while deserializing + private void resetLock() { + UNSAFE.putObjectVolatile(this, lockOffset, new ReentrantLock()); + } + private static final sun.misc.Unsafe UNSAFE; + private static final long lockOffset; + static { + try { + UNSAFE = sun.misc.Unsafe.getUnsafe(); + Class k = CopyOnWriteArrayList.class; + lockOffset = UNSAFE.objectFieldOffset + (k.getDeclaredField("lock")); + } catch (Exception e) { + throw new Error(e); + } + } +} + + diff --git a/week_04/17/DelayQueue b/week_04/17/DelayQueue new file mode 100644 index 0000000..1fd3962 --- /dev/null +++ b/week_04/17/DelayQueue @@ -0,0 +1,281 @@ +##DelayQueue---延时阻塞队列(一般用于定时任务) + 继承AbstractQueue + boolean add(E e); + remove(); + element() ; + clear(); + addAll(Collection c) + + + 实现BlockingQueue + boolean add(E e);----入队 + boolean offer(E e);----入队 + void put(E e) throws InterruptedException;--入队 + boolean offer(E e, long timeout, TimeUnit unit)--时间段入队 + throws InterruptedException; + + E take() throws InterruptedException;--出队 + E poll(long timeout, TimeUnit unit)--出队 + throws InterruptedException; + int remainingCapacity(); + boolean remove(Object o); + public boolean contains(Object o); + int drainTo(Collection c);--队列数据转移 + int drainTo(Collection c, int maxElements);--队列数据转移 + 可以看下阻塞队列这几个方法是不是一样的~~~ + + +##属性 + //有锁 + private final transient ReentrantLock lock = new ReentrantLock(); + //无界的优先级队列--初始化为长度11的数组 + private final PriorityQueue q = new PriorityQueue(); + //有线程 + private Thread leader = null; + //还有一个条件 + private final Condition available = lock.newCondition(); + +##构造 + //创建一个空的队列 + public DelayQueue() {} + + public DelayQueue(Collection c) { + this.addAll(c); + } + //该方法来只有AbstractQueue + public boolean addAll(Collection c) { + if (c == null) + throw new NullPointerException(); + if (c == this) + throw new IllegalArgumentException(); + boolean modified = false; + for (E e : c) + //这个add方法调用是offer,而offer,又是调用实现类的方法,所以,DelayQueue调用就是自己的offer方法 + if (add(e)) + modified = true; + return modified; + } + + +##入队方法 + public boolean add(E e) { + return offer(e); + } + public void put(E e) { + offer(e); + } + //因为是无界限的,所以永远不会阻塞,时间就用不上了 + public boolean offer(E e, long timeout, TimeUnit unit) { + return offer(e); + } + //真正的入队的方法 + public boolean offer(E e) { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + //q是一个无界优先级队列 + //把元素放入优先级队列中 + q.offer(e); + //如果优先级队列头是这个元素,后面没有其他节点了 + if (q.peek() == e) { + //指控leader + leader = null; + //唤醒等待中的 + available.signal(); + } + return true; + } finally { + lock.unlock(); + } + } + +##出队方法 + + 1. public E poll() { + final ReentrantLock lock = this.lock; + lock.lock(); + try { + //拿到堆顶的数据(也就是 应该第一个走的) + E first = q.peek(); + //这个数据是空的 或者这个数据还没有到期,返回 + if (first == null || first.getDelay(NANOSECONDS) > 0) + return null; + else + //出队--来源PriorityQueue + return q.poll(); + } finally { + lock.unlock(); + } + } + //出队--来源PriorityQueue + public E poll() { + //没有,返回空 + if (size == 0) + return null; + + int s = --size; + //mod的数量添加一次 + modCount++; + //把堆顶数据取出来 + E result = (E) queue[0]; + //堆地的数据 + E x = (E) queue[s]; + //把最后哪一个赋值为空 + queue[s] = null; + //里面还有值 + if (s != 0) + //排序(有条件,就条件排序,没有条件就自身条件排序) + siftDown(0, x); + //返回堆顶 + return result; + } + 2.public E take() throws InterruptedException { + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + try { + //自旋 + for (;;) { + //堆顶元素 + E first = q.peek(); + //队列是空的,就阻塞在这里一直等 + if (first == null) + available.await(); + else { + //有数据,过期了 + long delay = first.getDelay(NANOSECONDS); + if (delay <= 0) + //出队,然后排序 + return q.poll(); + + //没有过期,后面就要阻塞在这里等 + //等的时候,不要拿着引用, + first = null; // don't retain ref while waiting + //前面有等待的,跟着一起排队 + if (leader != null) + available.await(); + else { + //前面没有人了,该我了 + Thread thisThread = Thread.currentThread(); + leader = thisThread; + try { + //然后去拿这个节点(然后又跑到AQS这边去了,如果那边有同步队列,那么还是要乖乖的排队) + available.awaitNanos(delay); + } finally { + if (leader == thisThread) + leader = null; + } + } + } + } + } finally { + if (leader == null && q.peek() != null) + available.signal(); + lock.unlock(); + } + } + 3. + public E poll(long timeout, TimeUnit unit) throws InterruptedException { + //纳秒 + long nanos = unit.toNanos(timeout); + final ReentrantLock lock = this.lock; + lock.lockInterruptibly(); + try { + for (;;) { + //拿堆顶数据 + E first = q.peek(); + if (first == null) { + //没有数据且过期,就返回null; + + if (nanos <= 0) + return null; + else + //没有过期,就等nanos这么长 + nanos = available.awaitNanos(nanos); + } else { + //有数据,过期了就出队(算当前时间和等待时间的差) + long delay = first.getDelay(NANOSECONDS); + if (delay <= 0) + return q.poll(); + //等待时间到了也返回 + if (nanos <= 0) + return null; + //等待期间不用拿着引用 + first = null; // don't retain ref while waiting + //纳秒时间小于过期时间,前面有人在等 + if (nanos < delay || leader != null) + //继续等着 + nanos = available.awaitNanos(nanos); + else { + //该当前节点了 + Thread thisThread = Thread.currentThread(); + leader = thisThread; + try { + //去获取资源----但是有可能要去AQS同步队列中排位置 + long timeLeft = available.awaitNanos(delay); + nanos -= delay - timeLeft; + } finally { + //是leader是当前线程,就把leader设置为空。(当前线程用完了) + if (leader == thisThread) + leader = null; + } + } + } + } + } finally { + //堆顶还有最小节点,唤醒等待 + if (leader == null && q.peek() != null) + available.signal(); + lock.unlock(); + } + } + + 4. + + public int drainTo(Collection c) { + if (c == null) + throw new NullPointerException(); + if (c == this) + throw new IllegalArgumentException(); + + final ReentrantLock lock = this.lock; + lock.lock(); + try { + int n = 0; + //一直转,转到队列中没有为止 + for (E e; (e = peekExpired()) != null;) { + //把没有过期放到集合 + c.add(e); // In this order, in case add() throws. + //优先级队列 出队 + q.poll(); + //操作数+1; + ++n; + } + //返回操作数量 + return n; + } finally { + lock.unlock(); + } + } + //和上面一样,只是 从头开始拿maxElements 个 + public int drainTo(Collection c, int maxElements) { + if (c == null) + throw new NullPointerException(); + if (c == this) + throw new IllegalArgumentException(); + if (maxElements <= 0) + return 0; + final ReentrantLock lock = this.lock; + lock.lock(); + try { + int n = 0; + for (E e; n < maxElements && (e = peekExpired()) != null;) { + c.add(e); // In this order, in case add() throws. + q.poll(); + ++n; + } + return n; + } finally { + lock.unlock(); + } + } + \ No newline at end of file -- Gitee