ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ConcurrentHashMapV8.java
(Generate patch)

Comparing jsr166/src/jsr166e/ConcurrentHashMapV8.java (file contents):
Revision 1.26 by jsr166, Wed Sep 21 11:42:08 2011 UTC vs.
Revision 1.27 by dl, Sun Oct 2 22:01:06 2011 UTC

# Line 98 | Line 98 | public class ConcurrentHashMapV8<K, V>
98      private static final long serialVersionUID = 7249069246763182397L;
99  
100      /**
101 <     * A function computing a mapping from the given key to a value,
102 <     * or {@code null} if there is no mapping. This is a place-holder
103 <     * for an upcoming JDK8 interface.
101 >     * A function computing a mapping from the given key to a value.
102 >     * This is a place-holder for an upcoming JDK8 interface.
103       */
104      public static interface MappingFunction<K, V> {
105          /**
106 <         * Returns a value for the given key, or null if there is no
108 <         * mapping. If this function throws an (unchecked) exception,
109 <         * the exception is rethrown to its caller, and no mapping is
110 <         * recorded.  Because this function is invoked within
111 <         * atomicity control, the computation should be short and
112 <         * simple. The most common usage is to construct a new object
113 <         * serving as an initial mapped value.
106 >         * Returns a non-null value for the given key.
107           *
108           * @param key the (non-null) key
109 <         * @return a value, or null if none
109 >         * @return a non-null value
110           */
111          V map(K key);
112      }
113  
114 +    /**
115 +     * A function computing a new mapping given a key and its current
116 +     * mapped value (or {@code null} if there is no current
117 +     * mapping). This is a place-holder for an upcoming JDK8
118 +     * interface.
119 +     */
120 +    public static interface RemappingFunction<K, V> {
121 +        /**
122 +         * Returns a new value given a key and its current value.
123 +         *
124 +         * @param key the (non-null) key
125 +         * @param value the current value, or null if there is no mapping
126 +         * @return a non-null value
127 +         */
128 +        V remap(K key, V value);
129 +    }
130 +
131      /*
132       * Overview:
133       *
# Line 134 | Line 144 | public class ConcurrentHashMapV8<K, V>
144       * work off Object types. And similarly, so do the internal
145       * methods of auxiliary iterator and view classes.  All public
146       * generic typed methods relay in/out of these internal methods,
147 <     * supplying null-checks and casts as needed.
147 >     * supplying null-checks and casts as needed. This also allows
148 >     * many of the public methods to be factored into a smaller number
149 >     * of internal methods (although sadly not so for the five
150 >     * sprawling variants of put-related operations).
151       *
152       * The table is lazily initialized to a power-of-two size upon the
153       * first insertion.  Each bin in the table contains a list of
154 <     * Nodes (most often, zero or one Node).  Table accesses require
155 <     * volatile/atomic reads, writes, and CASes.  Because there is no
156 <     * other way to arrange this without adding further indirections,
157 <     * we use intrinsics (sun.misc.Unsafe) operations.  The lists of
158 <     * nodes within bins are always accurately traversable under
159 <     * volatile reads, so long as lookups check hash code and
160 <     * non-nullness of value before checking key equality.
154 >     * Nodes (most often, the list has only zero or one Node).  Table
155 >     * accesses require volatile/atomic reads, writes, and CASes.
156 >     * Because there is no other way to arrange this without adding
157 >     * further indirections, we use intrinsics (sun.misc.Unsafe)
158 >     * operations.  The lists of nodes within bins are always
159 >     * accurately traversable under volatile reads, so long as lookups
160 >     * check hash code and non-nullness of value before checking key
161 >     * equality.
162       *
163       * We use the top two bits of Node hash fields for control
164       * purposes -- they are available anyway because of addressing
165       * constraints.  As explained further below, these top bits are
166 <     * usd as follows:
166 >     * used as follows:
167       *  00 - Normal
168       *  01 - Locked
169       *  11 - Locked and may have a thread waiting for lock
# Line 158 | Line 172 | public class ConcurrentHashMapV8<K, V>
172       * The lower 30 bits of each Node's hash field contain a
173       * transformation (for better randomization -- method "spread") of
174       * the key's hash code, except for forwarding nodes, for which the
175 <     * lower bits are zero (and so always have hash field == "MOVED").
175 >     * lower bits are zero (and so always have hash field == MOVED).
176       *
177 <     * Insertion (via put or putIfAbsent) of the first node in an
177 >     * Insertion (via put or its variants) of the first node in an
178       * empty bin is performed by just CASing it to the bin.  This is
179       * by far the most common case for put operations.  Other update
180       * operations (insert, delete, and replace) require locks.  We do
# Line 179 | Line 193 | public class ConcurrentHashMapV8<K, V>
193       * validate that it is still the first node after locking it, and
194       * retry if not. Because new nodes are always appended to lists,
195       * once a node is first in a bin, it remains first until deleted
196 <     * or the bin becomes invalidated.  However, operations that only
197 <     * conditionally update may inspect nodes until the point of
198 <     * update. This is a converse of sorts to the lazy locking
199 <     * technique described by Herlihy & Shavit.
196 >     * or the bin becomes invalidated (upon resizing).  However,
197 >     * operations that only conditionally update may inspect nodes
198 >     * until the point of update. This is a converse of sorts to the
199 >     * lazy locking technique described by Herlihy & Shavit.
200       *
201       * The main disadvantage of per-bin locks is that other update
202       * operations on other nodes in a bin list protected by the same
# Line 266 | Line 280 | public class ConcurrentHashMapV8<K, V>
280       * The element count is maintained using a LongAdder, which avoids
281       * contention on updates but can encounter cache thrashing if read
282       * too frequently during concurrent access. To avoid reading so
283 <     * often, resizing is normally attempted only upon adding to a bin
284 <     * already holding two or more nodes. Under uniform hash
285 <     * distributions, the probability of this occurring at threshold
286 <     * is around 13%, meaning that only about 1 in 8 puts check
287 <     * threshold (and after resizing, many fewer do so). But this
288 <     * approximation has high variance for small table sizes, so we
289 <     * check on any collision for sizes <= 64.
283 >     * often, resizing is attempted either when a bin lock is
284 >     * contended, or upon adding to a bin already holding two or more
285 >     * nodes (checked before adding in the xIfAbsent methods, after
286 >     * adding in others). Under uniform hash distributions, the
287 >     * probability of this occurring at threshold is around 13%,
288 >     * meaning that only about 1 in 8 puts check threshold (and after
289 >     * resizing, many fewer do so). But this approximation has high
290 >     * variance for small table sizes, so we check on any collision
291 >     * for sizes <= 64. The bulk putAll operation further reduces
292 >     * contention by only committing count updates upon these size
293 >     * checks.
294       *
295       * Maintaining API and serialization compatibility with previous
296       * versions of this class introduces several oddities. Mainly: We
# Line 496 | Line 514 | public class ConcurrentHashMapV8<K, V>
514       */
515      private static final int spread(int h) {
516          // Apply base step of MurmurHash; see http://code.google.com/p/smhasher/
517 +        // Despite two multiplies, this is often faster than others
518 +        // with comparable bit-spread properties.
519          h ^= h >>> 16;
520          h *= 0x85ebca6b;
521          h ^= h >>> 13;
# Line 522 | Line 542 | public class ConcurrentHashMapV8<K, V>
542          return null;
543      }
544  
545 <    /** Implementation for put and putIfAbsent */
546 <    private final Object internalPut(Object k, Object v, boolean replace) {
545 >    /**
546 >     * Implementation for the four public remove/replace methods:
547 >     * Replaces node value with v, conditional upon match of cv if
548 >     * non-null.  If resulting value is null, delete.
549 >     */
550 >    private final Object internalReplace(Object k, Object v, Object cv) {
551          int h = spread(k.hashCode());
552 <        Object oldVal = null;               // previous value or null if none
552 >        Object oldVal = null;
553          for (Node[] tab = table;;) {
554 <            int i; Node f; int fh; Object fk, fv;
554 >            Node f; int i, fh;
555 >            if (tab == null ||
556 >                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
557 >                break;
558 >            else if ((fh = f.hash) == MOVED)
559 >                tab = (Node[])f.key;
560 >            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
561 >                break;                          // rules out possible existence
562 >            else if ((fh & LOCKED) != 0) {
563 >                checkForResize();               // try resizing if can't get lock
564 >                f.tryAwaitLock(tab, i);
565 >            }
566 >            else if (f.casHash(fh, fh | LOCKED)) {
567 >                boolean validated = false;
568 >                boolean deleted = false;
569 >                try {
570 >                    if (tabAt(tab, i) == f) {
571 >                        validated = true;
572 >                        for (Node e = f, pred = null;;) {
573 >                            Object ek, ev;
574 >                            if ((e.hash & HASH_BITS) == h &&
575 >                                ((ev = e.val) != null) &&
576 >                                ((ek = e.key) == k || k.equals(ek))) {
577 >                                if (cv == null || cv == ev || cv.equals(ev)) {
578 >                                    oldVal = ev;
579 >                                    if ((e.val = v) == null) {
580 >                                        deleted = true;
581 >                                        Node en = e.next;
582 >                                        if (pred != null)
583 >                                            pred.next = en;
584 >                                        else
585 >                                            setTabAt(tab, i, en);
586 >                                    }
587 >                                }
588 >                                break;
589 >                            }
590 >                            pred = e;
591 >                            if ((e = e.next) == null)
592 >                                break;
593 >                        }
594 >                    }
595 >                } finally {
596 >                    if (!f.casHash(fh | LOCKED, fh)) {
597 >                        f.hash = fh;
598 >                        synchronized(f) { f.notifyAll(); };
599 >                    }
600 >                }
601 >                if (validated) {
602 >                    if (deleted)
603 >                        counter.add(-1L);
604 >                    break;
605 >                }
606 >            }
607 >        }
608 >        return oldVal;
609 >    }
610 >
611 >    /*
612 >     * Internal versions of the five insertion methods, each a
613 >     * little more complicated than the last. All have
614 >     * the same basic structure as the first (internalPut):
615 >     *  1. If table uninitialized, create
616 >     *  2. If bin empty, try to CAS new node
617 >     *  3. If bin stale, use new table
618 >     *  4. Lock and validate; if valid, scan and add or update
619 >     *
620 >     * The others interweave other checks and/or alternative actions:
621 >     *  * Plain put checks for and performs resize after insertion.
622 >     *  * putIfAbsent prescans for mapping without lock (and fails to add
623 >     *    if present), which also makes pre-emptive resize checks worthwhile.
624 >     *  * computeIfAbsent extends form used in putIfAbsent with additional
625 >     *    mechanics to deal with, calls, potential exceptions and null
626 >     *    returns from function call.
627 >     *  * compute uses the same function-call mechanics, but without
628 >     *    the prescans
629 >     *  * putAll attempts to pre-allocate enough table space
630 >     *    and more lazily performs count updates and checks.
631 >     *
632 >     * Someday when details settle down a bit more, it might be worth
633 >     * some factoring to reduce sprawl.
634 >     */
635 >
636 >    /** Implementation for put */
637 >    private final Object internalPut(Object k, Object v) {
638 >        int h = spread(k.hashCode());
639 >        boolean checkSize = false;
640 >        for (Node[] tab = table;;) {
641 >            int i; Node f; int fh;
642              if (tab == null)
643                  tab = initTable();
644              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
# Line 536 | Line 647 | public class ConcurrentHashMapV8<K, V>
647              }
648              else if ((fh = f.hash) == MOVED)
649                  tab = (Node[])f.key;
650 <            else if (!replace && (fh & HASH_BITS) == h && (fv = f.val) != null &&
651 <                     ((fk = f.key) == k || k.equals(fk))) {
541 <                oldVal = fv;                // precheck 1st node for putIfAbsent
542 <                break;
543 <            }
544 <            else if ((fh & LOCKED) != 0)
650 >            else if ((fh & LOCKED) != 0) {
651 >                checkForResize();
652                  f.tryAwaitLock(tab, i);
653 +            }
654              else if (f.casHash(fh, fh | LOCKED)) {
655 +                Object oldVal = null;
656                  boolean validated = false;
657 <                boolean checkSize = false;
549 <                try {
657 >                try {                        // needed in case equals() throws
658                      if (tabAt(tab, i) == f) {
659                          validated = true;    // retry if 1st already deleted
660                          for (Node e = f;;) {
# Line 555 | Line 663 | public class ConcurrentHashMapV8<K, V>
663                                  (ev = e.val) != null &&
664                                  ((ek = e.key) == k || k.equals(ek))) {
665                                  oldVal = ev;
666 <                                if (replace)
559 <                                    e.val = v;
666 >                                e.val = v;
667                                  break;
668                              }
669                              Node last = e;
# Line 575 | Line 682 | public class ConcurrentHashMapV8<K, V>
682                      }
683                  }
684                  if (validated) {
685 <                    int sc;
686 <                    if (checkSize && tab.length < MAXIMUM_CAPACITY &&
580 <                        (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc)
581 <                        growTable();
685 >                    if (oldVal != null)
686 >                        return oldVal;
687                      break;
688                  }
689              }
690          }
691 <        if (oldVal == null)
692 <            counter.increment();             // update counter outside of locks
693 <        return oldVal;
691 >        counter.add(1L);
692 >        if (checkSize)
693 >            checkForResize();
694 >        return null;
695      }
696  
697 <    /**
698 <     * Implementation for the four public remove/replace methods:
593 <     * Replaces node value with v, conditional upon match of cv if
594 <     * non-null.  If resulting value is null, delete.
595 <     */
596 <    private final Object internalReplace(Object k, Object v, Object cv) {
697 >    /** Implementation for putIfAbsent */
698 >    private final Object internalPutIfAbsent(Object k, Object v) {
699          int h = spread(k.hashCode());
598        Object oldVal = null;
700          for (Node[] tab = table;;) {
701 <            Node f; int i, fh;
702 <            if (tab == null ||
703 <                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
704 <                break;
701 >            int i; Node f; int fh; Object fk, fv;
702 >            if (tab == null)
703 >                tab = initTable();
704 >            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
705 >                if (casTabAt(tab, i, null, new Node(h, k, v, null)))
706 >                    break;
707 >            }
708              else if ((fh = f.hash) == MOVED)
709                  tab = (Node[])f.key;
710 <            else if ((fh & HASH_BITS) != h && f.next == null) // precheck
711 <                break;                          // rules out possible existence
712 <            else if ((fh & LOCKED) != 0)
713 <                f.tryAwaitLock(tab, i);
714 <            else if (f.casHash(fh, fh | LOCKED)) {
715 <                boolean validated = false;
716 <                boolean deleted = false;
717 <                try {
718 <                    if (tabAt(tab, i) == f) {
719 <                        validated = true;
720 <                        for (Node e = f, pred = null;;) {
721 <                            Object ek, ev;
722 <                            if ((e.hash & HASH_BITS) == h &&
723 <                                ((ev = e.val) != null) &&
724 <                                ((ek = e.key) == k || k.equals(ek))) {
725 <                                if (cv == null || cv == ev || cv.equals(ev)) {
710 >            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
711 >                     ((fk = f.key) == k || k.equals(fk)))
712 >                return fv;
713 >            else {
714 >                Node g = f.next;
715 >                if (g != null) { // at least 2 nodes -- search and maybe resize
716 >                    for (Node e = g;;) {
717 >                        Object ek, ev;
718 >                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
719 >                            ((ek = e.key) == k || k.equals(ek)))
720 >                            return ev;
721 >                        if ((e = e.next) == null) {
722 >                            checkForResize();
723 >                            break;
724 >                        }
725 >                    }
726 >                }
727 >                if (((fh = f.hash) & LOCKED) != 0) {
728 >                    checkForResize();
729 >                    f.tryAwaitLock(tab, i);
730 >                }
731 >                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
732 >                    Object oldVal = null;
733 >                    boolean validated = false;
734 >                    try {
735 >                        if (tabAt(tab, i) == f) {
736 >                            validated = true;
737 >                            for (Node e = f;;) {
738 >                                Object ek, ev;
739 >                                if ((e.hash & HASH_BITS) == h &&
740 >                                    (ev = e.val) != null &&
741 >                                    ((ek = e.key) == k || k.equals(ek))) {
742                                      oldVal = ev;
743 <                                    if ((e.val = v) == null) {
744 <                                        deleted = true;
745 <                                        Node en = e.next;
746 <                                        if (pred != null)
747 <                                            pred.next = en;
748 <                                        else
629 <                                            setTabAt(tab, i, en);
630 <                                    }
743 >                                    break;
744 >                                }
745 >                                Node last = e;
746 >                                if ((e = e.next) == null) {
747 >                                    last.next = new Node(h, k, v, null);
748 >                                    break;
749                                  }
632                                break;
750                              }
751 <                            pred = e;
752 <                            if ((e = e.next) == null)
753 <                                break;
751 >                        }
752 >                    } finally {
753 >                        if (!f.casHash(fh | LOCKED, fh)) {
754 >                            f.hash = fh;
755 >                            synchronized(f) { f.notifyAll(); };
756                          }
757                      }
758 <                } finally {
759 <                    if (!f.casHash(fh | LOCKED, fh)) {
760 <                        f.hash = fh;
761 <                        synchronized (f) { f.notifyAll(); };
758 >                    if (validated) {
759 >                        if (oldVal != null)
760 >                            return oldVal;
761 >                        break;
762                      }
763                  }
764 <                if (validated) {
765 <                    if (deleted)
766 <                        counter.decrement();
764 >            }
765 >        }
766 >        counter.add(1L);
767 >        return null;
768 >    }
769 >
770 >    /** Implementation for computeIfAbsent */
771 >    private final Object internalComputeIfAbsent(K k,
772 >                                                 MappingFunction<? super K, ?> mf) {
773 >        int h = spread(k.hashCode());
774 >        Object val = null;
775 >        for (Node[] tab = table;;) {
776 >            Node f; int i, fh; Object fk, fv;
777 >            if (tab == null)
778 >                tab = initTable();
779 >            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
780 >                Node node = new Node(fh = h | LOCKED, k, null, null);
781 >                boolean validated = false;
782 >                if (casTabAt(tab, i, null, node)) {
783 >                    validated = true;
784 >                    try {
785 >                        if ((val = mf.map(k)) != null)
786 >                            node.val = val;
787 >                    } finally {
788 >                        if (val == null)
789 >                            setTabAt(tab, i, null);
790 >                        if (!node.casHash(fh, h)) {
791 >                            node.hash = h;
792 >                            synchronized(node) { node.notifyAll(); };
793 >                        }
794 >                    }
795 >                }
796 >                if (validated)
797                      break;
798 +            }
799 +            else if ((fh = f.hash) == MOVED)
800 +                tab = (Node[])f.key;
801 +            else if ((fh & HASH_BITS) == h && (fv = f.val) != null &&
802 +                     ((fk = f.key) == k || k.equals(fk)))
803 +                return fv;
804 +            else {
805 +                Node g = f.next;
806 +                if (g != null) {
807 +                    for (Node e = g;;) {
808 +                        Object ek, ev;
809 +                        if ((e.hash & HASH_BITS) == h && (ev = e.val) != null &&
810 +                            ((ek = e.key) == k || k.equals(ek)))
811 +                            return ev;
812 +                        if ((e = e.next) == null) {
813 +                            checkForResize();
814 +                            break;
815 +                        }
816 +                    }
817 +                }
818 +                if (((fh = f.hash) & LOCKED) != 0) {
819 +                    checkForResize();
820 +                    f.tryAwaitLock(tab, i);
821 +                }
822 +                else if (tabAt(tab, i) == f && f.casHash(fh, fh | LOCKED)) {
823 +                    boolean validated = false;
824 +                    try {
825 +                        if (tabAt(tab, i) == f) {
826 +                            validated = true;
827 +                            for (Node e = f;;) {
828 +                                Object ek, ev;
829 +                                if ((e.hash & HASH_BITS) == h &&
830 +                                    (ev = e.val) != null &&
831 +                                    ((ek = e.key) == k || k.equals(ek))) {
832 +                                    val = ev;
833 +                                    break;
834 +                                }
835 +                                Node last = e;
836 +                                if ((e = e.next) == null) {
837 +                                    if ((val = mf.map(k)) != null)
838 +                                        last.next = new Node(h, k, val, null);
839 +                                    break;
840 +                                }
841 +                            }
842 +                        }
843 +                    } finally {
844 +                        if (!f.casHash(fh | LOCKED, fh)) {
845 +                            f.hash = fh;
846 +                            synchronized(f) { f.notifyAll(); };
847 +                        }
848 +                    }
849 +                    if (validated)
850 +                        break;
851                  }
852              }
853          }
854 <        return oldVal;
854 >        if (val == null)
855 >            throw new NullPointerException();
856 >        counter.add(1L);
857 >        return val;
858      }
859  
860 <    /** Implementation for computeIfAbsent and compute. Like put, but messier. */
656 <    // Todo: Somehow reinstate non-termination check
860 >    /** Implementation for compute */
861      @SuppressWarnings("unchecked")
862 <    private final V internalCompute(K k,
863 <                                    MappingFunction<? super K, ? extends V> fn,
660 <                                    boolean replace) {
862 >    private final Object internalCompute(K k,
863 >                                         RemappingFunction<? super K, V> mf) {
864          int h = spread(k.hashCode());
865 <        V val = null;
865 >        Object val = null;
866          boolean added = false;
867 <        Node[] tab = table;
868 <        outer:for (;;) {
869 <            Node f; int i, fh; Object fk, fv;
867 >        boolean checkSize = false;
868 >        for (Node[] tab = table;;) {
869 >            Node f; int i, fh;
870              if (tab == null)
871                  tab = initTable();
872              else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
# Line 672 | Line 875 | public class ConcurrentHashMapV8<K, V>
875                  if (casTabAt(tab, i, null, node)) {
876                      validated = true;
877                      try {
878 <                        val = fn.map(k);
676 <                        if (val != null) {
878 >                        if ((val = mf.remap(k, null)) != null) {
879                              node.val = val;
880                              added = true;
881                          }
# Line 691 | Line 893 | public class ConcurrentHashMapV8<K, V>
893              }
894              else if ((fh = f.hash) == MOVED)
895                  tab = (Node[])f.key;
896 <            else if (!replace && (fh & HASH_BITS) == h && (fv = f.val) != null &&
897 <                     ((fk = f.key) == k || k.equals(fk))) {
696 <                if (tabAt(tab, i) == f) {
697 <                    val = (V)fv;
698 <                    break;
699 <                }
700 <            }
701 <            else if ((fh & LOCKED) != 0)
896 >            else if ((fh & LOCKED) != 0) {
897 >                checkForResize();
898                  f.tryAwaitLock(tab, i);
899 +            }
900              else if (f.casHash(fh, fh | LOCKED)) {
901                  boolean validated = false;
705                boolean checkSize = false;
902                  try {
903                      if (tabAt(tab, i) == f) {
904                          validated = true;
905                          for (Node e = f;;) {
906 <                            Object ek, ev, v;
906 >                            Object ek, ev;
907                              if ((e.hash & HASH_BITS) == h &&
908                                  (ev = e.val) != null &&
909                                  ((ek = e.key) == k || k.equals(ek))) {
910 <                                if (replace && (v = fn.map(k)) != null)
911 <                                    ev = e.val = v;
912 <                                val = (V)ev;
910 >                                val = mf.remap(k, (V)ev);
911 >                                if (val != null)
912 >                                    e.val = val;
913                                  break;
914                              }
915                              Node last = e;
916                              if ((e = e.next) == null) {
917 <                                if ((val = fn.map(k)) != null) {
917 >                                if ((val = mf.remap(k, null)) != null) {
918                                      last.next = new Node(h, k, val, null);
919                                      added = true;
920                                      if (last != f || tab.length <= 64)
# Line 734 | Line 930 | public class ConcurrentHashMapV8<K, V>
930                          synchronized (f) { f.notifyAll(); };
931                      }
932                  }
933 <                if (validated) {
738 <                    int sc;
739 <                    if (checkSize && tab.length < MAXIMUM_CAPACITY &&
740 <                        (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc)
741 <                        growTable();
933 >                if (validated)
934                      break;
743                }
935              }
936          }
937 <        if (added)
938 <            counter.increment();
937 >        if (added) {
938 >            counter.add(1L);
939 >            if (checkSize)
940 >                checkForResize();
941 >        }
942 >        else if (val == null)
943 >            throw new NullPointerException();
944          return val;
945      }
946  
947 <    /**
948 <     * Implementation for clear. Steps through each bin, removing all nodes.
949 <     */
950 <    private final void internalClear() {
951 <        long delta = 0L; // negative number of deletions
952 <        int i = 0;
953 <        Node[] tab = table;
954 <        while (tab != null && i < tab.length) {
955 <            int fh;
956 <            Node f = tabAt(tab, i);
957 <            if (f == null)
958 <                ++i;
959 <            else if ((fh = f.hash) == MOVED)
960 <                tab = (Node[])f.key;
961 <            else if ((fh & LOCKED) != 0)
962 <                f.tryAwaitLock(tab, i);
963 <            else if (f.casHash(fh, fh | LOCKED)) {
964 <                boolean validated = false;
965 <                try {
966 <                    if (tabAt(tab, i) == f) {
967 <                        validated = true;
968 <                        for (Node e = f; e != null; e = e.next) {
773 <                            if (e.val != null) { // currently always true
774 <                                e.val = null;
775 <                                --delta;
776 <                            }
947 >    /** Implementation for putAll */
948 >    private final void internalPutAll(Map<?, ?> m) {
949 >        tryPresize(m.size());
950 >        long delta = 0L;     // number of uncommitted additions
951 >        boolean npe = false; // to throw exception on exit for nulls
952 >        try {                // to clean up counts on other exceptions
953 >            for (Map.Entry<?, ?> entry : m.entrySet()) {
954 >                Object k, v;
955 >                if (entry == null || (k = entry.getKey()) == null ||
956 >                    (v = entry.getValue()) == null) {
957 >                    npe = true;
958 >                    break;
959 >                }
960 >                int h = spread(k.hashCode());
961 >                for (Node[] tab = table;;) {
962 >                    int i; Node f; int fh;
963 >                    if (tab == null)
964 >                        tab = initTable();
965 >                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
966 >                        if (casTabAt(tab, i, null, new Node(h, k, v, null))) {
967 >                            ++delta;
968 >                            break;
969                          }
778                        setTabAt(tab, i, null);
970                      }
971 <                } finally {
972 <                    if (!f.casHash(fh | LOCKED, fh)) {
973 <                        f.hash = fh;
974 <                        synchronized (f) { f.notifyAll(); };
971 >                    else if ((fh = f.hash) == MOVED)
972 >                        tab = (Node[])f.key;
973 >                    else if ((fh & LOCKED) != 0) {
974 >                        counter.add(delta);
975 >                        delta = 0L;
976 >                        checkForResize();
977 >                        f.tryAwaitLock(tab, i);
978 >                    }
979 >                    else if (f.casHash(fh, fh | LOCKED)) {
980 >                        boolean validated = false;
981 >                        boolean tooLong = false;
982 >                        try {
983 >                            if (tabAt(tab, i) == f) {
984 >                                validated = true;
985 >                                for (Node e = f;;) {
986 >                                    Object ek, ev;
987 >                                    if ((e.hash & HASH_BITS) == h &&
988 >                                        (ev = e.val) != null &&
989 >                                        ((ek = e.key) == k || k.equals(ek))) {
990 >                                        e.val = v;
991 >                                        break;
992 >                                    }
993 >                                    Node last = e;
994 >                                    if ((e = e.next) == null) {
995 >                                        ++delta;
996 >                                        last.next = new Node(h, k, v, null);
997 >                                        break;
998 >                                    }
999 >                                    tooLong = true;
1000 >                                }
1001 >                            }
1002 >                        } finally {
1003 >                            if (!f.casHash(fh | LOCKED, fh)) {
1004 >                                f.hash = fh;
1005 >                                synchronized(f) { f.notifyAll(); };
1006 >                            }
1007 >                        }
1008 >                        if (validated) {
1009 >                            if (tooLong) {
1010 >                                counter.add(delta);
1011 >                                delta = 0L;
1012 >                                checkForResize();
1013 >                            }
1014 >                            break;
1015 >                        }
1016                      }
1017                  }
786                if (validated)
787                    ++i;
1018              }
1019 +        } finally {
1020 +            if (delta != 0)
1021 +                counter.add(delta);
1022          }
1023 <        counter.add(delta);
1023 >        if (npe)
1024 >            throw new NullPointerException();
1025      }
1026  
1027 <    /* ----------------Table Initialization and Resizing -------------- */
1027 >    /* ---------------- Table Initialization and Resizing -------------- */
1028  
1029      /**
1030       * Returns a power of two table size for the given desired capacity.
# Line 819 | Line 1053 | public class ConcurrentHashMapV8<K, V>
1053                      if ((tab = table) == null) {
1054                          int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
1055                          tab = table = new Node[n];
1056 <                        sc = n - (n >>> 2) - 1;
1056 >                        sc = n - (n >>> 2);
1057                      }
1058                  } finally {
1059                      sizeCtl = sc;
# Line 831 | Line 1065 | public class ConcurrentHashMapV8<K, V>
1065      }
1066  
1067      /**
1068 <     * If not already resizing, creates next table and transfers bins.
1069 <     * Rechecks occupancy after a transfer to see if another resize is
1070 <     * already needed because resizings are lagging additions.
1071 <     */
1072 <    private final void growTable() {
1073 <        int sc = sizeCtl;
1074 <        if (sc >= 0 && UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1068 >     * If table is too small and not already resizing, creates next
1069 >     * table and transfers bins.  Rechecks occupancy after a transfer
1070 >     * to see if another resize is already needed because resizings
1071 >     * are lagging additions.
1072 >     */
1073 >    private final void checkForResize() {
1074 >        Node[] tab; int n, sc;
1075 >        while ((tab = table) != null &&
1076 >               (n = tab.length) < MAXIMUM_CAPACITY &&
1077 >               (sc = sizeCtl) >= 0 && counter.sum() >= (long)sc &&
1078 >               UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1079              try {
1080 <                Node[] tab; int n;
843 <                while ((tab = table) != null &&
844 <                       (n = tab.length) > 0 && n < MAXIMUM_CAPACITY &&
845 <                       counter.sum() >= (long)sc) {
1080 >                if (tab == table) {
1081                      table = rebuild(tab);
1082 <                    sc = (n << 1) - (n >>> 1) - 1;
1082 >                    sc = (n << 1) - (n >>> 1);
1083                  }
1084              } finally {
1085                  sizeCtl = sc;
# Line 852 | Line 1087 | public class ConcurrentHashMapV8<K, V>
1087          }
1088      }
1089  
1090 +    /**
1091 +     * Tries to presize table to accommodate the given number of elements.
1092 +     *
1093 +     * @param size number of elements (doesn't need to be perfectly accurate)
1094 +     */
1095 +    private final void tryPresize(int size) {
1096 +        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1097 +            tableSizeFor(size + (size >>> 1) + 1);
1098 +        int sc;
1099 +        while ((sc = sizeCtl) >= 0) {
1100 +            Node[] tab = table; int n;
1101 +            if (tab == null || (n = tab.length) == 0) {
1102 +                n = (sc > c)? sc : c;
1103 +                if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1104 +                    try {
1105 +                        if (table == tab) {
1106 +                            table = new Node[n];
1107 +                            sc = n - (n >>> 2);
1108 +                        }
1109 +                    } finally {
1110 +                        sizeCtl = sc;
1111 +                    }
1112 +                }
1113 +            }
1114 +            else if (c <= sc || n >= MAXIMUM_CAPACITY)
1115 +                break;
1116 +            else if (UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1117 +                try {
1118 +                    if (table == tab) {
1119 +                        table = rebuild(tab);
1120 +                        sc = (n << 1) - (n >>> 1);
1121 +                    }
1122 +                } finally {
1123 +                    sizeCtl = sc;
1124 +                }
1125 +            }
1126 +        }
1127 +    }
1128 +
1129      /*
1130       * Moves and/or copies the nodes in each bin to new table. See
1131       * above for explanation.
# Line 961 | Line 1235 | public class ConcurrentHashMapV8<K, V>
1235          }
1236      }
1237  
1238 +    /**
1239 +     * Implementation for clear. Steps through each bin, removing all
1240 +     * nodes.
1241 +     */
1242 +    private final void internalClear() {
1243 +        long delta = 0L; // negative number of deletions
1244 +        int i = 0;
1245 +        Node[] tab = table;
1246 +        while (tab != null && i < tab.length) {
1247 +            int fh;
1248 +            Node f = tabAt(tab, i);
1249 +            if (f == null)
1250 +                ++i;
1251 +            else if ((fh = f.hash) == MOVED)
1252 +                tab = (Node[])f.key;
1253 +            else if ((fh & LOCKED) != 0) {
1254 +                counter.add(delta); // opportunistically update count
1255 +                delta = 0L;
1256 +                f.tryAwaitLock(tab, i);
1257 +            }
1258 +            else if (f.casHash(fh, fh | LOCKED)) {
1259 +                boolean validated = false;
1260 +                try {
1261 +                    if (tabAt(tab, i) == f) {
1262 +                        validated = true;
1263 +                        for (Node e = f; e != null; e = e.next) {
1264 +                            if (e.val != null) { // currently always true
1265 +                                e.val = null;
1266 +                                --delta;
1267 +                            }
1268 +                        }
1269 +                        setTabAt(tab, i, null);
1270 +                    }
1271 +                } finally {
1272 +                    if (!f.casHash(fh | LOCKED, fh)) {
1273 +                        f.hash = fh;
1274 +                        synchronized(f) { f.notifyAll(); };
1275 +                    }
1276 +                }
1277 +                if (validated)
1278 +                    ++i;
1279 +            }
1280 +        }
1281 +        if (delta != 0)
1282 +            counter.add(delta);
1283 +    }
1284 +
1285 +
1286      /* ----------------Table Traversal -------------- */
1287  
1288      /**
# Line 982 | Line 1304 | public class ConcurrentHashMapV8<K, V>
1304       * value, or key-value pairs as return values of Iterator.next(),
1305       * and encapsulate the it.next check as hasNext();
1306       *
1307 <     * The iterator visits each valid node that was reachable upon
1308 <     * iterator construction once. It might miss some that were added
1309 <     * to a bin after the bin was visited, which is OK wrt consistency
1310 <     * guarantees. Maintaining this property in the face of possible
1311 <     * ongoing resizes requires a fair amount of bookkeeping state
1312 <     * that is difficult to optimize away amidst volatile accesses.
1313 <     * Even so, traversal maintains reasonable throughput.
1307 >     * The iterator visits once each still-valid node that was
1308 >     * reachable upon iterator construction. It might miss some that
1309 >     * were added to a bin after the bin was visited, which is OK wrt
1310 >     * consistency guarantees. Maintaining this property in the face
1311 >     * of possible ongoing resizes requires a fair amount of
1312 >     * bookkeeping state that is difficult to optimize away amidst
1313 >     * volatile accesses.  Even so, traversal maintains reasonable
1314 >     * throughput.
1315       *
1316       * Normally, iteration proceeds bin-by-bin traversing lists.
1317       * However, if the table has been resized, then all future steps
# Line 1026 | Line 1349 | public class ConcurrentHashMapV8<K, V>
1349              this.tab = tab;
1350              baseSize = (tab == null) ? 0 : tab.length;
1351              baseLimit = (hi <= baseSize) ? hi : baseSize;
1352 <            index = baseIndex = lo;
1352 >            index = baseIndex = (lo >= 0) ? lo : 0;
1353              next = null;
1354              advance();
1355          }
# Line 1090 | Line 1413 | public class ConcurrentHashMapV8<K, V>
1413      public ConcurrentHashMapV8(Map<? extends K, ? extends V> m) {
1414          this.counter = new LongAdder();
1415          this.sizeCtl = DEFAULT_CAPACITY;
1416 <        putAll(m);
1416 >        internalPutAll(m);
1417      }
1418  
1419      /**
# Line 1257 | Line 1580 | public class ConcurrentHashMapV8<K, V>
1580      public V put(K key, V value) {
1581          if (key == null || value == null)
1582              throw new NullPointerException();
1583 <        return (V)internalPut(key, value, true);
1583 >        return (V)internalPut(key, value);
1584      }
1585  
1586      /**
# Line 1271 | Line 1594 | public class ConcurrentHashMapV8<K, V>
1594      public V putIfAbsent(K key, V value) {
1595          if (key == null || value == null)
1596              throw new NullPointerException();
1597 <        return (V)internalPut(key, value, false);
1597 >        return (V)internalPutIfAbsent(key, value);
1598      }
1599  
1600      /**
# Line 1282 | Line 1605 | public class ConcurrentHashMapV8<K, V>
1605       * @param m mappings to be stored in this map
1606       */
1607      public void putAll(Map<? extends K, ? extends V> m) {
1608 <        if (m == null)
1286 <            throw new NullPointerException();
1287 <        /*
1288 <         * If uninitialized, try to preallocate big enough table
1289 <         */
1290 <        if (table == null) {
1291 <            int size = m.size();
1292 <            int n = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
1293 <                tableSizeFor(size + (size >>> 1) + 1);
1294 <            int sc = sizeCtl;
1295 <            if (n < sc)
1296 <                n = sc;
1297 <            if (sc >= 0 &&
1298 <                UNSAFE.compareAndSwapInt(this, sizeCtlOffset, sc, -1)) {
1299 <                try {
1300 <                    if (table == null) {
1301 <                        table = new Node[n];
1302 <                        sc = n - (n >>> 2) - 1;
1303 <                    }
1304 <                } finally {
1305 <                    sizeCtl = sc;
1306 <                }
1307 <            }
1308 <        }
1309 <        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
1310 <            Object ek = e.getKey(), ev = e.getValue();
1311 <            if (ek == null || ev == null)
1312 <                throw new NullPointerException();
1313 <            internalPut(ek, ev, true);
1314 <        }
1608 >        internalPutAll(m);
1609      }
1610  
1611      /**
1612       * If the specified key is not already associated with a value,
1613 <     * computes its value using the given mappingFunction, and if
1614 <     * non-null, enters it into the map.  This is equivalent to
1615 <     *  <pre> {@code
1613 >     * computes its value using the given mappingFunction and
1614 >     * enters it into the map.  This is equivalent to
1615 >     * <pre> {@code
1616       * if (map.containsKey(key))
1617       *   return map.get(key);
1618       * value = mappingFunction.map(key);
1619 <     * if (value != null)
1326 <     *   map.put(key, value);
1619 >     * map.put(key, value);
1620       * return value;}</pre>
1621       *
1622 <     * except that the action is performed atomically.  Some attempted
1623 <     * update operations on this map by other threads may be blocked
1624 <     * while computation is in progress, so the computation should be
1625 <     * short and simple, and must not attempt to update any other
1626 <     * mappings of this Map. The most appropriate usage is to
1627 <     * construct a new object serving as an initial mapped value, or
1628 <     * memoized result, as in:
1622 >     * except that the action is performed atomically.  If the
1623 >     * function returns {@code null} (in which case a {@code
1624 >     * NullPointerException} is thrown), or the function itself throws
1625 >     * an (unchecked) exception, the exception is rethrown to its
1626 >     * caller, and no mapping is recorded.  Some attempted update
1627 >     * operations on this map by other threads may be blocked while
1628 >     * computation is in progress, so the computation should be short
1629 >     * and simple, and must not attempt to update any other mappings
1630 >     * of this Map. The most appropriate usage is to construct a new
1631 >     * object serving as an initial mapped value, or memoized result,
1632 >     * as in:
1633 >     *
1634       *  <pre> {@code
1635       * map.computeIfAbsent(key, new MappingFunction<K, V>() {
1636       *   public V map(K k) { return new Value(f(k)); }});}</pre>
# Line 1340 | Line 1638 | public class ConcurrentHashMapV8<K, V>
1638       * @param key key with which the specified value is to be associated
1639       * @param mappingFunction the function to compute a value
1640       * @return the current (existing or computed) value associated with
1641 <     *         the specified key, or {@code null} if the computation
1642 <     *         returned {@code null}
1643 <     * @throws NullPointerException if the specified key or mappingFunction
1346 <     *         is null
1641 >     *         the specified key.
1642 >     * @throws NullPointerException if the specified key, mappingFunction,
1643 >     *         or computed value is null
1644       * @throws IllegalStateException if the computation detectably
1645       *         attempts a recursive update to this map that would
1646       *         otherwise never complete
1647       * @throws RuntimeException or Error if the mappingFunction does so,
1648       *         in which case the mapping is left unestablished
1649       */
1650 +    @SuppressWarnings("unchecked")
1651      public V computeIfAbsent(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
1652          if (key == null || mappingFunction == null)
1653              throw new NullPointerException();
1654 <        return internalCompute(key, mappingFunction, false);
1654 >        return (V)internalComputeIfAbsent(key, mappingFunction);
1655      }
1656  
1657      /**
1658 <     * Computes the value associated with the given key using the given
1659 <     * mappingFunction, and if non-null, enters it into the map.  This
1660 <     * is equivalent to
1658 >     * Computes and enters a new mapping value given a key and
1659 >     * its current mapped value (or {@code null} if there is no current
1660 >     * mapping). This is equivalent to
1661       *  <pre> {@code
1662 <     * value = mappingFunction.map(key);
1663 <     * if (value != null)
1366 <     *   map.put(key, value);
1367 <     * else
1368 <     *   value = map.get(key);
1369 <     * return value;}</pre>
1662 >     *  map.put(key, remappingFunction.remap(key, map.get(key));
1663 >     * }</pre>
1664       *
1665 <     * except that the action is performed atomically.  Some attempted
1665 >     * except that the action is performed atomically.  If the
1666 >     * function returns {@code null} (in which case a {@code
1667 >     * NullPointerException} is thrown), or the function itself throws
1668 >     * an (unchecked) exception, the exception is rethrown to its
1669 >     * caller, and current mapping is left unchanged.  Some attempted
1670       * update operations on this map by other threads may be blocked
1671       * while computation is in progress, so the computation should be
1672       * short and simple, and must not attempt to update any other
1673 <     * mappings of this Map.
1673 >     * mappings of this Map. For example, to either create or
1674 >     * append new messages to a value mapping:
1675 >     *
1676 >     * <pre> {@code
1677 >     * Map<Key, String> map = ...;
1678 >     * final String msg = ...;
1679 >     * map.compute(key, new RemappingFunction<Key, String>() {
1680 >     *   public String remap(Key k, String v) {
1681 >     *    return (v == null) ? msg : v + msg;});}</pre>
1682       *
1683       * @param key key with which the specified value is to be associated
1684 <     * @param mappingFunction the function to compute a value
1685 <     * @return the current value associated with
1686 <     *         the specified key, or {@code null} if the computation
1687 <     *         returned {@code null} and the value was not otherwise present
1688 <     * @throws NullPointerException if the specified key or mappingFunction
1383 <     *         is null
1684 >     * @param remappingFunction the function to compute a value
1685 >     * @return the new value associated with
1686 >     *         the specified key.
1687 >     * @throws NullPointerException if the specified key or remappingFunction
1688 >     *         or computed value is null
1689       * @throws IllegalStateException if the computation detectably
1690       *         attempts a recursive update to this map that would
1691       *         otherwise never complete
1692       * @throws RuntimeException or Error if the mappingFunction does so,
1693       *         in which case the mapping is unchanged
1694       */
1695 <    public V compute(K key, MappingFunction<? super K, ? extends V> mappingFunction) {
1696 <        if (key == null || mappingFunction == null)
1695 >    @SuppressWarnings("unchecked")
1696 >    public V compute(K key, RemappingFunction<? super K, V> remappingFunction) {
1697 >        if (key == null || remappingFunction == null)
1698              throw new NullPointerException();
1699 <        return internalCompute(key, mappingFunction, true);
1699 >        return (V)internalCompute(key, remappingFunction);
1700      }
1701  
1702      /**
# Line 2103 | Line 2409 | public class ConcurrentHashMapV8<K, V>
2409              }
2410              if (!init) { // Can only happen if unsafely published.
2411                  while (p != null) {
2412 <                    internalPut(p.key, p.val, true);
2412 >                    internalPut(p.key, p.val);
2413                      p = p.next;
2414                  }
2415              }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines