changeset 7312:388b4d4cae3b

Merge
author lana
date Wed, 05 Jun 2013 12:31:59 -0700
parents f272934d41fb e857b2a3ecee
children 080449feeca9
files test/java/util/stream/test/org/openjdk/tests/java/util/stream/SpliteratorLateBindingFailFastTest.java test/java/util/stream/test/org/openjdk/tests/java/util/stream/SpliteratorTraversingAndSplittingTest.java
diffstat 146 files changed, 14545 insertions(+), 3916 deletions(-) [+]
line wrap: on
line diff
--- a/make/java/management/Exportedfiles.gmk	Wed Jun 05 12:30:02 2013 -0700
+++ b/make/java/management/Exportedfiles.gmk	Wed Jun 05 12:31:59 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 
 FILES_export = \
 	sun/management/ClassLoadingImpl.java \
+	sun/management/DiagnosticCommandImpl.java \
 	sun/management/FileSystemImpl.java \
 	sun/management/Flag.java \
 	sun/management/GarbageCollectorImpl.java \
--- a/make/java/management/FILES_c.gmk	Wed Jun 05 12:30:02 2013 -0700
+++ b/make/java/management/FILES_c.gmk	Wed Jun 05 12:31:59 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 
 FILES_c = \
 	ClassLoadingImpl.c \
+	DiagnosticCommandImpl.c \
 	FileSystemImpl.c \
 	Flag.c \
 	GarbageCollectorImpl.c \
--- a/make/java/management/mapfile-vers	Wed Jun 05 12:30:02 2013 -0700
+++ b/make/java/management/mapfile-vers	Wed Jun 05 12:31:59 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -39,6 +39,10 @@
 	    Java_com_sun_management_UnixOperatingSystem_getTotalSwapSpaceSize;
 	    Java_com_sun_management_UnixOperatingSystem_initialize;
 	    Java_sun_management_ClassLoadingImpl_setVerboseClass;
+            Java_sun_management_DiagnosticCommandImpl_executeDiagnosticCommand;
+            Java_sun_management_DiagnosticCommandImpl_getDiagnosticCommands;
+            Java_sun_management_DiagnosticCommandImpl_getDiagnosticCommandInfo;
+	    Java_sun_management_DiagnosticCommandImpl_setNotificationEnabled;
 	    Java_sun_management_FileSystemImpl_isAccessUserOnly0;
 	    Java_sun_management_Flag_getAllFlagNames;
 	    Java_sun_management_Flag_getFlags;
--- a/make/tools/CharsetMapping/EUC_KR.map	Wed Jun 05 12:30:02 2013 -0700
+++ b/make/tools/CharsetMapping/EUC_KR.map	Wed Jun 05 12:31:59 2013 -0700
@@ -5,6 +5,8 @@
 # (2)Added 2 new codepoints (KS X 1001:1998)
 #     0xA2E6	0x20AC	# EURO Sign
 #     0xA2E7	0x00AE	# Registered Sign
+# (3) KS X 1001:2002
+#     0xA2E8	0x327E  # CIRCLED KOREAN CHARACTER JUEUI (Postal Code Mark)
 #
 0x00	0x0000
 0x01	0x0001
@@ -295,6 +297,7 @@
 #
 0xA2E6	0x20AC	# EURO Sign
 0xA2E7	0x00AE	# Registered Sign
+0xA2E8	0x327E  # CIRCLED KOREAN CHARACTER JUEUI
 #
 0xA2E0	0x2116	# NUMERO SIGN
 0xA2E1	0x33C7	# SQUARE CO
--- a/make/tools/src/build/tools/generatebreakiteratordata/CharSet.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/make/tools/src/build/tools/generatebreakiteratordata/CharSet.java	Wed Jun 05 12:31:59 2013 -0700
@@ -39,6 +39,7 @@
 
 package build.tools.generatebreakiteratordata;
 
+import java.util.Arrays;
 import java.util.Hashtable;
 
 /**
@@ -701,7 +702,14 @@
      * the exact same characters as this one
      */
     public boolean equals(Object that) {
-        return (that instanceof CharSet) && chars.equals(((CharSet)that).chars);
+        return (that instanceof CharSet) && Arrays.equals(chars, ((CharSet)that).chars);
+    }
+
+    /**
+     * Returns the hash code for this set of characters
+     */
+    public int hashCode() {
+       return Arrays.hashCode(chars);
     }
 
     /**
--- a/makefiles/CompileJavaClasses.gmk	Wed Jun 05 12:30:02 2013 -0700
+++ b/makefiles/CompileJavaClasses.gmk	Wed Jun 05 12:31:59 2013 -0700
@@ -342,7 +342,7 @@
 		DISABLE_SJAVAC:=true,\
 		SRC:=$(JDK_TOPDIR)/src/macosx/native/jobjc/src/core/java \
 		     $(JDK_TOPDIR)/src/macosx/native/jobjc/src/runtime-additions/java \
-		     $(JDK_OUTPUTDIR)/gensrc, \
+		     $(JDK_OUTPUTDIR)/gensrc_jobjc/src, \
 		INCLUDES := com/apple/jobjc,\
                 EXCLUDES := tests/java/com/apple/jobjc,\
 		BIN:=$(JDK_OUTPUTDIR)/jobjc_classes,\
@@ -355,7 +355,7 @@
 		SETUP:=GENERATE_JDKBYTECODE,\
 		SRC:=$(JDK_TOPDIR)/src/macosx/native/jobjc/src/core/java \
 		     $(JDK_TOPDIR)/src/macosx/native/jobjc/src/runtime-additions/java \
-		     $(JDK_OUTPUTDIR)/gensrc, \
+		     $(JDK_OUTPUTDIR)/gensrc_jobjc/src, \
 		INCLUDES := com/apple/jobjc,\
                 EXCLUDES := tests/java/com/apple/jobjc,\
 		BIN:=$(JDK_OUTPUTDIR)/jobjc_classes_headers,\
--- a/makefiles/GensrcBuffer.gmk	Wed Jun 05 12:30:02 2013 -0700
+++ b/makefiles/GensrcBuffer.gmk	Wed Jun 05 12:31:59 2013 -0700
@@ -69,6 +69,9 @@
 		$1_fulltype := character
 		$1_Fulltype := Character
 		$1_category := integralType
+                $1_streams  := streamableType
+                $1_streamtype := int
+                $1_Streamtype := Int
 		$1_LBPV     := 1
 	endif
 
@@ -97,7 +100,7 @@
 		$1_Type     := Long
 		$1_fulltype := long
 		$1_Fulltype := Long
-		$1_category := integralType
+		$1_category := integralType	
 		$1_LBPV     := 3
 	endif
 
@@ -231,10 +234,13 @@
 	$(TOOL_SPP) < $$($1_SRC) > $$($1_OUT).tmp \
 		-K$$($1_type) \
 		-K$$($1_category) \
+		-K$$($1_streams) \
 		-Dtype=$$($1_type) \
 		-DType=$$($1_Type) \
 		-Dfulltype=$$($1_fulltype) \
 		-DFulltype=$$($1_Fulltype) \
+                -Dstreamtype=$$($1_streamtype) \
+                -DStreamtype=$$($1_Streamtype) \
 		-Dx=$$($1_x) \
 		-Dmemtype=$$($1_memtype) \
 		-DMemtype=$$($1_Memtype) \
--- a/makefiles/mapfiles/libmanagement/mapfile-vers	Wed Jun 05 12:30:02 2013 -0700
+++ b/makefiles/mapfiles/libmanagement/mapfile-vers	Wed Jun 05 12:31:59 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -39,6 +39,10 @@
 	    Java_com_sun_management_UnixOperatingSystem_getTotalSwapSpaceSize;
 	    Java_com_sun_management_UnixOperatingSystem_initialize;
 	    Java_sun_management_ClassLoadingImpl_setVerboseClass;
+            Java_sun_management_DiagnosticCommandImpl_executeDiagnosticCommand;
+            Java_sun_management_DiagnosticCommandImpl_getDiagnosticCommands;
+            Java_sun_management_DiagnosticCommandImpl_getDiagnosticCommandInfo;
+            Java_sun_management_DiagnosticCommandImpl_setNotificationEnabled;
 	    Java_sun_management_FileSystemImpl_isAccessUserOnly0;
 	    Java_sun_management_Flag_getAllFlagNames;
 	    Java_sun_management_Flag_getFlags;
--- a/src/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/DHKeyAgreement.java	Wed Jun 05 12:31:59 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -403,8 +403,9 @@
             }
             return skey;
         } else if (algorithm.equals("TlsPremasterSecret")) {
-            // return entire secret
-            return new SecretKeySpec(secret, "TlsPremasterSecret");
+            // remove leading zero bytes per RFC 5246 Section 8.1.2
+            return new SecretKeySpec(
+                        KeyUtil.trimZeroes(secret), "TlsPremasterSecret");
         } else {
             throw new NoSuchAlgorithmException("Unsupported secret key "
                                                + "algorithm: "+ algorithm);
--- a/src/share/classes/com/sun/crypto/provider/HmacPKCS12PBESHA1.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/HmacPKCS12PBESHA1.java	Wed Jun 05 12:31:59 2013 -0700
@@ -86,12 +86,13 @@
             throw new InvalidKeyException("SecretKey of PBE type required");
         }
         if (params == null) {
-            // generate default for salt and iteration count if necessary
-            if (salt == null) {
-                salt = new byte[20];
-                SunJCE.getRandom().nextBytes(salt);
+            // should not auto-generate default values since current
+            // javax.crypto.Mac api does not have any method for caller to
+            // retrieve the generated defaults.
+            if ((salt == null) || (iCount == 0)) {
+                throw new InvalidAlgorithmParameterException
+                    ("PBEParameterSpec required for salt and iteration count");
             }
-            if (iCount == 0) iCount = 100;
         } else if (!(params instanceof PBEParameterSpec)) {
             throw new InvalidAlgorithmParameterException
                 ("PBEParameterSpec type required");
--- a/src/share/classes/com/sun/crypto/provider/PBMAC1Core.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/PBMAC1Core.java	Wed Jun 05 12:31:59 2013 -0700
@@ -42,12 +42,10 @@
  */
 abstract class PBMAC1Core extends HmacCore {
 
-    private static final int DEFAULT_SALT_LENGTH = 20;
-    private static final int DEFAULT_COUNT = 4096;
-
+    // NOTE: this class inherits the Cloneable interface from HmacCore
+    // Need to override clone() if mutable fields are added.
     private final String kdfAlgo;
     private final String hashAlgo;
-    private final PBKDF2Core kdf;
     private final int blockLength; // in octets
 
     /**
@@ -56,13 +54,15 @@
      */
     PBMAC1Core(String kdfAlgo, String hashAlgo, int blockLength)
         throws NoSuchAlgorithmException {
-
         super(hashAlgo, blockLength);
         this.kdfAlgo = kdfAlgo;
         this.hashAlgo = hashAlgo;
         this.blockLength = blockLength;
+    }
 
-        switch(kdfAlgo) {
+    private static PBKDF2Core getKDFImpl(String algo) {
+        PBKDF2Core kdf = null;
+        switch(algo) {
         case "HmacSHA1":
                 kdf = new PBKDF2Core.HmacSHA1();
                 break;
@@ -79,9 +79,10 @@
                 kdf = new PBKDF2Core.HmacSHA512();
                 break;
         default:
-                throw new NoSuchAlgorithmException(
-                    "No MAC implementation for " + kdfAlgo);
+                throw new ProviderException(
+                    "No MAC implementation for " + algo);
         }
+        return kdf;
     }
 
     /**
@@ -120,12 +121,13 @@
             throw new InvalidKeyException("SecretKey of PBE type required");
         }
         if (params == null) {
-            // generate default for salt and iteration count if necessary
-            if (salt == null) {
-                salt = new byte[DEFAULT_SALT_LENGTH];
-                SunJCE.getRandom().nextBytes(salt);
+            // should not auto-generate default values since current
+            // javax.crypto.Mac api does not have any method for caller to
+            // retrieve the generated defaults.
+            if ((salt == null) || (iCount == 0)) {
+                throw new InvalidAlgorithmParameterException
+                    ("PBEParameterSpec required for salt and iteration count");
             }
-            if (iCount == 0) iCount = DEFAULT_COUNT;
         } else if (!(params instanceof PBEParameterSpec)) {
             throw new InvalidAlgorithmParameterException
                 ("PBEParameterSpec type required");
@@ -168,7 +170,7 @@
         java.util.Arrays.fill(passwdChars, ' ');
 
         SecretKey s = null;
-
+        PBKDF2Core kdf = getKDFImpl(kdfAlgo);
         try {
             s = kdf.engineGenerateSecret(pbeSpec);
 
--- a/src/share/classes/com/sun/crypto/provider/SunJCE.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/com/sun/crypto/provider/SunJCE.java	Wed Jun 05 12:31:59 2013 -0700
@@ -731,10 +731,11 @@
                     put("Mac.HmacSHA384 SupportedKeyFormats", "RAW");
                     put("Mac.HmacSHA512 SupportedKeyFormats", "RAW");
                     put("Mac.HmacPBESHA1 SupportedKeyFormats", "RAW");
-                    put("Mac.HmacPBESHA224 SupportedKeyFormats", "RAW");
-                    put("Mac.HmacPBESHA256 SupportedKeyFormats", "RAW");
-                    put("Mac.HmacPBESHA384 SupportedKeyFormats", "RAW");
-                    put("Mac.HmacPBESHA512 SupportedKeyFormats", "RAW");
+                    put("Mac.PBEWithHmacSHA1 SupportedKeyFormatS", "RAW");
+                    put("Mac.PBEWithHmacSHA224 SupportedKeyFormats", "RAW");
+                    put("Mac.PBEWithHmacSHA256 SupportedKeyFormats", "RAW");
+                    put("Mac.PBEWithHmacSHA384 SupportedKeyFormats", "RAW");
+                    put("Mac.PBEWithHmacSHA512 SupportedKeyFormats", "RAW");
                     put("Mac.SslMacMD5 SupportedKeyFormats", "RAW");
                     put("Mac.SslMacSHA1 SupportedKeyFormats", "RAW");
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/com/sun/management/DiagnosticCommandMBean.java	Wed Jun 05 12:31:59 2013 -0700
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.management;
+
+import java.lang.management.PlatformManagedObject;
+import javax.management.DynamicMBean;
+
+/**
+ * Management interface for the diagnostic commands for the HotSpot Virtual Machine.
+ *
+ * <p>The {code DiagnosticCommandMBean} is registered to the
+ * {@linkplain java.lang.management.ManagementFactory#getPlatformMBeanServer
+ * platform MBeanServer} as are other platform MBeans.
+ *
+ * <p>The {@link javax.management.ObjectName ObjectName} for uniquely identifying
+ * the diagnostic MBean within an MBeanServer is:
+ * <blockquote>
+ *    {@code com.sun.management:type=DiagnosticCommand}
+ * </blockquote>
+ *
+ * <p>This MBean is a {@link javax.management.DynamicMBean DynamicMBean}
+ * and also a {@link javax.management.NotificationEmitter}.
+ * The {@code DiagnosticCommandMBean} is generated at runtime and is subject to
+ * modifications during the lifetime of the Java virtual machine.
+ *
+ * A <em>diagnostic command</em> is represented as an operation of
+ * the {@code DiagnosticCommandMBean} interface. Each diagnostic command has:
+ * <ul>
+ * <li>the diagnostic command name which is the name being referenced in
+ *     the HotSpot Virtual Machine</li>
+ * <li>the MBean operation name which is the
+ *     {@linkplain javax.management.MBeanOperationInfo#getName() name}
+ *     generated for the diagnostic command operation invocation.
+ *     The MBean operation name is implementation dependent</li>
+ * </ul>
+ *
+ * The recommended way to transform a diagnostic command name into a MBean
+ * operation name is as follows:
+ * <ul>
+ * <li>All characters from the first one to the first dot are set to be
+ *      lower-case characters</li>
+ * <li>Every dot or underline character is removed and the following
+ *   character is set to be an upper-case character</li>
+ * <li>All other characters are copied without modification</li>
+ * </ul>
+ *
+ * <p>The diagnostic command name is always provided with the meta-data on the
+ * operation in a field named {@code dcmd.name} (see below).
+ *
+ * <p>A diagnostic command may or may not support options or arguments.
+ * All the operations return {@code String} and either take
+ * no parameter for operations that do not support any option or argument,
+ * or take a {@code String[]} parameter for operations that support at least
+ * one option or argument.
+ * Each option or argument must be stored in a single String.
+ * Options or arguments split across several String instances are not supported.
+ *
+ * <p>The distinction between options and arguments: options are identified by
+ * the option name while arguments are identified by their position in the
+ * command line. Options and arguments are processed in the order of the array
+ * passed to the invocation method.
+ *
+ * <p>Like any operation of a dynamic MBean, each of these operations is
+ * described by {@link javax.management.MBeanOperationInfo MBeanOperationInfo}
+ * instance. Here's the values returned by this object:
+ * <ul>
+ *  <li>{@link javax.management.MBeanOperationInfo#getName() getName()}
+ *      returns the operation name generated from the diagnostic command name</li>
+ *  <li>{@link javax.management.MBeanOperationInfo#getDescription() getDescription()}
+ *      returns the diagnostic command description
+ *      (the same as the one return in the 'help' command)</li>
+ *  <li>{@link javax.management.MBeanOperationInfo#getImpact() getImpact()}
+ *      returns <code>ACTION_INFO</code></li>
+ *  <li>{@link javax.management.MBeanOperationInfo#getReturnType() getReturnType()}
+ *      returns {@code java.lang.String}</li>
+ *  <li>{@link javax.management.MBeanOperationInfo#getDescriptor() getDescriptor()}
+ *      returns a Descriptor instance (see below)</li>
+ * </ul>
+ *
+ * <p>The {@link javax.management.Descriptor Descriptor}
+ * is a collection of fields containing additional
+ * meta-data for a JMX element. A field is a name and an associated value.
+ * The additional meta-data provided for an operation associated with a
+ * diagnostic command are described in the table below:
+ * <p>
+ *
+ * <table border="1" cellpadding="5">
+ *   <tr>
+ *     <th>Name</th><th>Type</th><th>Description</th>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.name</td><td>String</td>
+ *     <td>The original diagnostic command name (not the operation name)</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.description</td><td>String</td>
+ *     <td>The diagnostic command description</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.help</td><td>String</td>
+ *     <td>The full help message for this diagnostic command (same output as
+ *          the one produced by the 'help' command)</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.vmImpact</td><td>String</td>
+ *     <td>The impact of the diagnostic command,
+ *      this value is the same as the one printed in the 'impact'
+ *      section of the help message of the diagnostic command, and it
+ *      is different from the getImpact() of the MBeanOperationInfo</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.enabled</td><td>boolean</td>
+ *     <td>True if the diagnostic command is enabled, false otherwise</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.permissionClass</td><td>String</td>
+ *     <td>Some diagnostic command might require a specific permission to be
+ *          executed, in addition to the MBeanPermission to invoke their
+ *          associated MBean operation. This field returns the fully qualified
+ *          name of the permission class or null if no permission is required
+ *   </td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.permissionName</td><td>String</td>
+ *     <td>The fist argument of the permission required to execute this
+ *          diagnostic command or null if no permission is required</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.permissionAction</td><td>String</td>
+ *     <td>The second argument of the permission required to execute this
+ *          diagnostic command or null if the permission constructor has only
+ *          one argument (like the ManagementPermission) or if no permission
+ *          is required</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.arguments</td><td>Descriptor</td>
+ *     <td>A Descriptor instance containing the descriptions of options and
+ *          arguments supported by the diagnostic command (see below)</td>
+ *   </tr>
+ * </table>
+ * <p>
+ *
+ * <p>The description of parameters (options or arguments) of a diagnostic
+ * command is provided within a Descriptor instance. In this Descriptor,
+ * each field name is a parameter name, and each field value is itself
+ * a Descriptor instance. The fields provided in this second Descriptor
+ * instance are described in the table below:
+ *
+ * <table border="1" cellpadding="5">
+ *   <tr>
+ *     <th>Name</th><th>Type</th><th>Description</th>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.arg.name</td><td>String</td>
+ *     <td>The name of the parameter</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.arg.type</td><td>String</td>
+ *     <td>The type of the parameter. The returned String is the name of a type
+ *          recognized by the diagnostic command parser. These types are not
+ *          Java types and are implementation dependent.
+ *          </td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.arg.description</td><td>String</td>
+ *     <td>The parameter description</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.arg.isMandatory</td><td>boolean</td>
+ *     <td>True if the parameter is mandatory, false otherwise</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.arg.isOption</td><td>boolean</td>
+ *     <td>True if the parameter is an option, false if it is an argument</td>
+ *   </tr>
+ *   <tr>
+ *     <td>dcmd.arg.isMultiple</td><td>boolean</td>
+ *     <td>True if the parameter can be specified several times, false
+ *          otherwise</td>
+ *   </tr>
+ * </table>
+ *
+ * <p>When the set of diagnostic commands currently supported by the Java
+ * Virtual Machine is modified, the {@code DiagnosticCommandMBean} emits
+ * a {@link javax.management.Notification} with a
+ * {@linkplain javax.management.Notification#getType() type} of
+ * <a href="{@docRoot}/../../../../api/javax/management/MBeanInfo.html#info-changed">
+ * {@code "jmx.mbean.info.changed"}</a> and a
+ * {@linkplain javax.management.Notification#getUserData() userData} that
+ * is the new {@code MBeanInfo}.
+ *
+ * @since 8
+ */
+public interface DiagnosticCommandMBean extends DynamicMBean
+{
+
+}
--- a/src/share/classes/java/lang/Integer.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/lang/Integer.java	Wed Jun 05 12:31:59 2013 -0700
@@ -26,7 +26,6 @@
 package java.lang;
 
 import java.lang.annotation.Native;
-import java.util.Properties;
 
 /**
  * The {@code Integer} class wraps a value of the primitive type
@@ -185,7 +184,7 @@
      * @since 1.8
      */
     public static String toUnsignedString(int i, int radix) {
-        return Long.toString(toUnsignedLong(i), radix);
+        return Long.toUnsignedString(toUnsignedLong(i), radix);
     }
 
     /**
@@ -307,20 +306,39 @@
     /**
      * Convert the integer to an unsigned number.
      */
-    private static String toUnsignedString0(int i, int shift) {
-        char[] buf = new char[32];
-        int charPos = 32;
+    private static String toUnsignedString0(int val, int shift) {
+        // assert shift > 0 && shift <=5 : "Illegal shift value";
+        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
+        int chars = Math.max(((mag + (shift - 1)) / shift), 1);
+        char[] buf = new char[chars];
+
+        formatUnsignedInt(val, shift, buf, 0, chars);
+
+        // Use special constructor which takes over "buf".
+        return new String(buf, true);
+    }
+
+    /**
+     * Format a long (treated as unsigned) into a character buffer.
+     * @param val the unsigned int to format
+     * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
+     * @param buf the character buffer to write to
+     * @param offset the offset in the destination buffer to start at
+     * @param len the number of characters to write
+     * @return the lowest character  location used
+     */
+     static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
+        int charPos = len;
         int radix = 1 << shift;
         int mask = radix - 1;
         do {
-            buf[--charPos] = digits[i & mask];
-            i >>>= shift;
-        } while (i != 0);
+            buf[offset + --charPos] = Integer.digits[val & mask];
+            val >>>= shift;
+        } while (val != 0 && charPos > 0);
 
-        return new String(buf, charPos, (32 - charPos));
+        return charPos;
     }
 
-
     final static char [] DigitTens = {
         '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
         '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
@@ -875,6 +893,7 @@
      * Returns the value of this {@code Integer} as a {@code long}
      * after a widening primitive conversion.
      * @jls 5.1.2 Widening Primitive Conversions
+     * @see Integer#toUnsignedLong(int)
      */
     public long longValue() {
         return (long)value;
--- a/src/share/classes/java/lang/Long.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/lang/Long.java	Wed Jun 05 12:31:59 2013 -0700
@@ -28,6 +28,7 @@
 import java.lang.annotation.Native;
 import java.math.*;
 
+
 /**
  * The {@code Long} class wraps a value of the primitive type {@code
  * long} in an object. An object of type {@code Long} contains a
@@ -344,18 +345,39 @@
     }
 
     /**
-     * Convert the integer to an unsigned number.
+     * Format a long (treated as unsigned) into a String.
+     * @param val the value to format
+     * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
      */
-    private static String toUnsignedString0(long i, int shift) {
-        char[] buf = new char[64];
-        int charPos = 64;
+    static String toUnsignedString0(long val, int shift) {
+        // assert shift > 0 && shift <=5 : "Illegal shift value";
+        int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
+        int chars = Math.max(((mag + (shift - 1)) / shift), 1);
+        char[] buf = new char[chars];
+
+        formatUnsignedLong(val, shift, buf, 0, chars);
+        return new String(buf, true);
+    }
+
+    /**
+     * Format a long (treated as unsigned) into a character buffer.
+     * @param val the unsigned long to format
+     * @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
+     * @param buf the character buffer to write to
+     * @param offset the offset in the destination buffer to start at
+     * @param len the number of characters to write
+     * @return the lowest character location used
+     */
+     static int formatUnsignedLong(long val, int shift, char[] buf, int offset, int len) {
+        int charPos = len;
         int radix = 1 << shift;
-        long mask = radix - 1;
+        int mask = radix - 1;
         do {
-            buf[--charPos] = Integer.digits[(int)(i & mask)];
-            i >>>= shift;
-        } while (i != 0);
-        return new String(buf, charPos, (64 - charPos));
+            buf[offset + --charPos] = Integer.digits[((int) val) & mask];
+            val >>>= shift;
+        } while (val != 0 && charPos > 0);
+
+        return charPos;
     }
 
     /**
--- a/src/share/classes/java/lang/management/ManagementFactory.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/lang/management/ManagementFactory.java	Wed Jun 05 12:31:59 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,7 +42,9 @@
 import java.util.Collections;
 import java.util.List;
 import java.util.Set;
+import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Map;
 import java.security.AccessController;
 import java.security.Permission;
 import java.security.PrivilegedAction;
@@ -482,6 +484,11 @@
                     }
                 }
             }
+            HashMap<ObjectName, DynamicMBean> dynmbeans =
+                    ManagementFactoryHelper.getPlatformDynamicMBeans();
+            for (Map.Entry<ObjectName, DynamicMBean> e : dynmbeans.entrySet()) {
+                addDynamicMBean(platformMBeanServer, e.getValue(), e.getKey());
+            }
         }
         return platformMBeanServer;
     }
@@ -825,4 +832,24 @@
         }
     }
 
+    /**
+     * Registers a DynamicMBean.
+     */
+    private static void addDynamicMBean(final MBeanServer mbs,
+                                        final DynamicMBean dmbean,
+                                        final ObjectName on) {
+        try {
+            AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
+                @Override
+                public Void run() throws InstanceAlreadyExistsException,
+                                         MBeanRegistrationException,
+                                         NotCompliantMBeanException {
+                    mbs.registerMBean(dmbean, on);
+                    return null;
+                }
+            });
+        } catch (PrivilegedActionException e) {
+            throw new RuntimeException(e.getException());
+        }
+    }
 }
--- a/src/share/classes/java/net/HttpCookie.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/net/HttpCookie.java	Wed Jun 05 12:31:59 2013 -0700
@@ -128,8 +128,7 @@
      *         a {@code String} specifying the value of the cookie
      *
      * @throws  IllegalArgumentException
-     *          if the cookie name contains illegal characters or it is one of
-     *          the tokens reserved for use by the cookie protocol
+     *          if the cookie name contains illegal characters
      * @throws  NullPointerException
      *          if {@code name} is {@code null}
      *
@@ -142,7 +141,7 @@
 
     private HttpCookie(String name, String value, String header) {
         name = name.trim();
-        if (name.length() == 0 || !isToken(name)) {
+        if (name.length() == 0 || !isToken(name) || name.charAt(0) == '$') {
             throw new IllegalArgumentException("Illegal cookie name");
         }
 
@@ -170,9 +169,8 @@
      * @return  a List of cookie parsed from header line string
      *
      * @throws  IllegalArgumentException
-     *          if header string violates the cookie specification's syntax, or
-     *          the cookie name contains illegal characters, or the cookie name
-     *          is one of the tokens reserved for use by the cookie protocol
+     *          if header string violates the cookie specification's syntax or
+     *          the cookie name contains illegal characters.
      * @throws  NullPointerException
      *          if the header string is {@code null}
      */
--- a/src/share/classes/java/net/HttpURLPermission.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/net/HttpURLPermission.java	Wed Jun 05 12:31:59 2013 -0700
@@ -377,7 +377,7 @@
             throw new IllegalArgumentException ("unexpected URL scheme");
         }
         if (!u.getSchemeSpecificPart().equals("*")) {
-            u = URI.create(scheme + "://" + u.getAuthority() + u.getPath());
+            u = URI.create(scheme + "://" + u.getRawAuthority() + u.getRawPath());
         }
         return u;
     }
--- a/src/share/classes/java/nio/Buffer.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/nio/Buffer.java	Wed Jun 05 12:31:59 2013 -0700
@@ -25,6 +25,7 @@
 
 package java.nio;
 
+import java.util.Spliterator;
 
 /**
  * A container for data of a specific primitive type.
@@ -173,6 +174,13 @@
 
 public abstract class Buffer {
 
+    /**
+     * The characteristics of Spliterators that traverse and split elements
+     * maintained in Buffers.
+     */
+    static final int SPLITERATOR_CHARACTERISTICS =
+        Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED;
+
     // Invariants: mark <= position <= limit <= capacity
     private int mark = -1;
     private int position = 0;
--- a/src/share/classes/java/nio/ByteBufferAs-X-Buffer.java.template	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/nio/ByteBufferAs-X-Buffer.java.template	Wed Jun 05 12:31:59 2013 -0700
@@ -115,6 +115,12 @@
         return Bits.get$Type$$BO$(bb, ix(checkIndex(i)));
     }
 
+#if[streamableType]
+   $type$ getUnchecked(int i) {
+        return Bits.get$Type$$BO$(bb, ix(i));
+    }
+#end[streamableType]
+
 #end[rw]
 
     public $Type$Buffer put($type$ x) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/nio/CharBufferSpliterator.java	Wed Jun 05 12:31:59 2013 -0700
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+* particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.nio;
+
+import java.util.Comparator;
+import java.util.Spliterator;
+import java.util.function.IntConsumer;
+
+/**
+ * A Spliterator.OfInt for sources that traverse and split elements
+ * maintained in a CharBuffer.
+ *
+ * @implNote
+ * The implementation is based on the code for the Array-based spliterators.
+ */
+class CharBufferSpliterator implements Spliterator.OfInt {
+    private final CharBuffer buffer;
+    private int index;   // current index, modified on advance/split
+    private final int limit;
+
+    CharBufferSpliterator(CharBuffer buffer) {
+        this(buffer, buffer.position(), buffer.limit());
+    }
+
+    CharBufferSpliterator(CharBuffer buffer, int origin, int limit) {
+        assert origin <= limit;
+        this.buffer = buffer;
+        this.index = (origin <= limit) ? origin : limit;
+        this.limit = limit;
+    }
+
+    @Override
+    public OfInt trySplit() {
+        int lo = index, mid = (lo + limit) >>> 1;
+        return (lo >= mid)
+               ? null
+               : new CharBufferSpliterator(buffer, lo, index = mid);
+    }
+
+    @Override
+    public void forEachRemaining(IntConsumer action) {
+        if (action == null)
+            throw new NullPointerException();
+        CharBuffer cb = buffer;
+        int i = index;
+        int hi = limit;
+        index = hi;
+        while (i < hi) {
+            action.accept(cb.getUnchecked(i++));
+        }
+    }
+
+    @Override
+    public boolean tryAdvance(IntConsumer action) {
+        if (action == null)
+            throw new NullPointerException();
+        if (index >= 0 && index < limit) {
+            action.accept(buffer.getUnchecked(index++));
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    public long estimateSize() {
+        return (long)(limit - index);
+    }
+
+    @Override
+    public int characteristics() {
+        return Buffer.SPLITERATOR_CHARACTERISTICS;
+    }
+}
--- a/src/share/classes/java/nio/Direct-X-Buffer.java.template	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/nio/Direct-X-Buffer.java.template	Wed Jun 05 12:31:59 2013 -0700
@@ -253,6 +253,12 @@
         return $fromBits$($swap$(unsafe.get$Swaptype$(ix(checkIndex(i)))));
     }
 
+#if[streamableType]
+    $type$ getUnchecked(int i) {
+        return $fromBits$($swap$(unsafe.get$Swaptype$(ix(i))));
+    }
+#end[streamableType]
+
     public $Type$Buffer get($type$[] dst, int offset, int length) {
 #if[rw]
         if ((length << $LG_BYTES_PER_VALUE$) > Bits.JNI_COPY_TO_ARRAY_THRESHOLD) {
--- a/src/share/classes/java/nio/Heap-X-Buffer.java.template	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/nio/Heap-X-Buffer.java.template	Wed Jun 05 12:31:59 2013 -0700
@@ -139,6 +139,12 @@
         return hb[ix(checkIndex(i))];
     }
 
+#if[streamableType]
+    $type$ getUnchecked(int i) {
+	return hb[ix(i)];
+    }
+#end[streamableType]
+
     public $Type$Buffer get($type$[] dst, int offset, int length) {
         checkBounds(offset, length, dst.length);
         if (length > remaining())
--- a/src/share/classes/java/nio/StringCharBuffer.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/nio/StringCharBuffer.java	Wed Jun 05 12:31:59 2013 -0700
@@ -77,6 +77,10 @@
         return str.charAt(checkIndex(index) + offset);
     }
 
+    char getUnchecked(int index) {
+        return str.charAt(index + offset);
+    }
+
     // ## Override bulk get methods for better performance
 
     public final CharBuffer put(char c) {
--- a/src/share/classes/java/nio/X-Buffer.java.template	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/nio/X-Buffer.java.template	Wed Jun 05 12:31:59 2013 -0700
@@ -30,6 +30,11 @@
 #if[char]
 import java.io.IOException;
 #end[char]
+#if[streamableType]
+import java.util.Spliterator;
+import java.util.stream.StreamSupport;
+import java.util.stream.$Streamtype$Stream;
+#end[streamableType]
 
 /**
  * $A$ $type$ buffer.
@@ -589,6 +594,19 @@
      */
     public abstract $type$ get(int index);
 
+#if[streamableType]
+    /**
+     * Absolute <i>get</i> method.  Reads the $type$ at the given
+     * index without any validation of the index.
+     *
+     * @param  index
+     *         The index from which the $type$ will be read
+     *
+     * @return  The $type$ at the given index
+     */
+    abstract $type$ getUnchecked(int index);   // package-private
+#end[streamableType]
+
     /**
      * Absolute <i>put</i> method&nbsp;&nbsp;<i>(optional operation)</i>.
      *
@@ -1458,4 +1476,16 @@
 
 #end[byte]
 
+#if[streamableType]
+
+#if[char]
+    @Override
+#end[char]
+    public $Streamtype$Stream $type$s() {
+        return StreamSupport.$streamtype$Stream(() -> new $Type$BufferSpliterator(this),
+            Buffer.SPLITERATOR_CHARACTERISTICS);
+    }
+
+#end[streamableType]
+
 }
--- a/src/share/classes/java/security/AccessControlContext.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/security/AccessControlContext.java	Wed Jun 05 12:31:59 2013 -0700
@@ -85,6 +85,15 @@
 
     private DomainCombiner combiner = null;
 
+    // limited privilege scope
+    private Permission permissions[];
+    private AccessControlContext parent;
+    private boolean isWrapped;
+
+    // is constrained by limited privilege scope?
+    private boolean isLimited;
+    private ProtectionDomain limitedContext[];
+
     private static boolean debugInit = false;
     private static Debug debug = null;
 
@@ -178,14 +187,79 @@
 
     /**
      * package private for AccessController
+     *
+     * This "argument wrapper" context will be passed as the actual context
+     * parameter on an internal doPrivileged() call used in the implementation.
      */
-    AccessControlContext(ProtectionDomain context[], DomainCombiner combiner) {
+    AccessControlContext(ProtectionDomain caller, DomainCombiner combiner,
+        AccessControlContext parent, AccessControlContext context,
+        Permission[] perms)
+    {
+        /*
+         * Combine the domains from the doPrivileged() context into our
+         * wrapper context, if necessary.
+         */
+        ProtectionDomain[] callerPDs = null;
+        if (caller != null) {
+             callerPDs = new ProtectionDomain[] { caller };
+        }
         if (context != null) {
-            this.context = context.clone();
+            if (combiner != null) {
+                this.context = combiner.combine(callerPDs, context.context);
+            } else {
+                this.context = combine(callerPDs, context.context);
+            }
+        } else {
+            /*
+             * Call combiner even if there is seemingly nothing to combine.
+             */
+            if (combiner != null) {
+                this.context = combiner.combine(callerPDs, null);
+            } else {
+                this.context = combine(callerPDs, null);
+            }
         }
         this.combiner = combiner;
+
+        Permission[] tmp = null;
+        if (perms != null) {
+            tmp = new Permission[perms.length];
+            for (int i=0; i < perms.length; i++) {
+                if (perms[i] == null) {
+                    throw new NullPointerException("permission can't be null");
+                }
+
+                /*
+                 * An AllPermission argument is equivalent to calling
+                 * doPrivileged() without any limit permissions.
+                 */
+                if (perms[i].getClass() == AllPermission.class) {
+                    parent = null;
+                }
+                tmp[i] = perms[i];
+            }
+        }
+
+        /*
+         * For a doPrivileged() with limited privilege scope, initialize
+         * the relevant fields.
+         *
+         * The limitedContext field contains the union of all domains which
+         * are enclosed by this limited privilege scope. In other words,
+         * it contains all of the domains which could potentially be checked
+         * if none of the limiting permissions implied a requested permission.
+         */
+        if (parent != null) {
+            this.limitedContext = combine(parent.context, parent.limitedContext);
+            this.isLimited = true;
+            this.isWrapped = true;
+            this.permissions = tmp;
+            this.parent = parent;
+            this.privilegedContext = context; // used in checkPermission2()
+        }
     }
 
+
     /**
      * package private constructor for AccessController.getContext()
      */
@@ -260,6 +334,13 @@
         if (sm != null) {
             sm.checkPermission(SecurityConstants.GET_COMBINER_PERMISSION);
         }
+        return getCombiner();
+    }
+
+    /**
+     * package private for AccessController
+     */
+    DomainCombiner getCombiner() {
         return combiner;
     }
 
@@ -335,8 +416,10 @@
            or the first domain was a Privileged system domain. This
            is to make the common case for system code very fast */
 
-        if (context == null)
+        if (context == null) {
+            checkPermission2(perm);
             return;
+        }
 
         for (int i=0; i< context.length; i++) {
             if (context[i] != null &&  !context[i].implies(perm)) {
@@ -370,20 +453,108 @@
             debug.println("access allowed "+perm);
         }
 
-        return;
+        checkPermission2(perm);
+    }
+
+    /*
+     * Check the domains associated with the limited privilege scope.
+     */
+    private void checkPermission2(Permission perm) {
+        if (!isLimited) {
+            return;
+        }
+
+        /*
+         * Check the doPrivileged() context parameter, if present.
+         */
+        if (privilegedContext != null) {
+            privilegedContext.checkPermission2(perm);
+        }
+
+        /*
+         * Ignore the limited permissions and parent fields of a wrapper
+         * context since they were already carried down into the unwrapped
+         * context.
+         */
+        if (isWrapped) {
+            return;
+        }
+
+        /*
+         * Try to match any limited privilege scope.
+         */
+        if (permissions != null) {
+            Class<?> permClass = perm.getClass();
+            for (int i=0; i < permissions.length; i++) {
+                Permission limit = permissions[i];
+                if (limit.getClass().equals(permClass) && limit.implies(perm)) {
+                    return;
+                }
+            }
+        }
+
+        /*
+         * Check the limited privilege scope up the call stack or the inherited
+         * parent thread call stack of this ACC.
+         */
+        if (parent != null) {
+            /*
+             * As an optimization, if the parent context is the inherited call
+             * stack context from a parent thread then checking the protection
+             * domains of the parent context is redundant since they have
+             * already been merged into the child thread's context by
+             * optimize(). When parent is set to an inherited context this
+             * context was not directly created by a limited scope
+             * doPrivileged() and it does not have its own limited permissions.
+             */
+            if (permissions == null) {
+                parent.checkPermission2(perm);
+            } else {
+                parent.checkPermission(perm);
+            }
+        }
     }
 
     /**
      * Take the stack-based context (this) and combine it with the
-     * privileged or inherited context, if need be.
+     * privileged or inherited context, if need be. Any limited
+     * privilege scope is flagged regardless of whether the assigned
+     * context comes from an immediately enclosing limited doPrivileged().
+     * The limited privilege scope can indirectly flow from the inherited
+     * parent thread or an assigned context previously captured by getContext().
      */
     AccessControlContext optimize() {
         // the assigned (privileged or inherited) context
         AccessControlContext acc;
+        DomainCombiner combiner = null;
+        AccessControlContext parent = null;
+        Permission[] permissions = null;
+
         if (isPrivileged) {
             acc = privilegedContext;
+            if (acc != null) {
+                /*
+                 * If the context is from a limited scope doPrivileged() then
+                 * copy the permissions and parent fields out of the wrapper
+                 * context that was created to hold them.
+                 */
+                if (acc.isWrapped) {
+                    permissions = acc.permissions;
+                    parent = acc.parent;
+                }
+            }
         } else {
             acc = AccessController.getInheritedAccessControlContext();
+            if (acc != null) {
+                /*
+                 * If the inherited context is constrained by a limited scope
+                 * doPrivileged() then set it as our parent so we will process
+                 * the non-domain-related state.
+                 */
+                if (acc.isLimited) {
+                    parent = acc;
+                }
+            }
         }
 
         // this.context could be null if only system code is on the stack;
@@ -393,53 +564,98 @@
         // acc.context could be null if only system code was involved;
         // in that case, ignore the assigned context
         boolean skipAssigned = (acc == null || acc.context == null);
+        ProtectionDomain[] assigned = (skipAssigned) ? null : acc.context;
+        ProtectionDomain[] pd;
+
+        // if there is no enclosing limited privilege scope on the stack or
+        // inherited from a parent thread
+        boolean skipLimited = ((acc == null || !acc.isWrapped) && parent == null);
 
         if (acc != null && acc.combiner != null) {
             // let the assigned acc's combiner do its thing
-            return goCombiner(context, acc);
+            if (getDebug() != null) {
+                debug.println("AccessControlContext invoking the Combiner");
+            }
+
+            // No need to clone current and assigned.context
+            // combine() will not update them
+            combiner = acc.combiner;
+            pd = combiner.combine(context, assigned);
+        } else {
+            if (skipStack) {
+                if (skipAssigned) {
+                    calculateFields(acc, parent, permissions);
+                    return this;
+                } else if (skipLimited) {
+                    return acc;
+                }
+            } else if (assigned != null) {
+                if (skipLimited) {
+                    // optimization: if there is a single stack domain and
+                    // that domain is already in the assigned context; no
+                    // need to combine
+                    if (context.length == 1 && context[0] == assigned[0]) {
+                        return acc;
+                    }
+                }
+            }
+
+            pd = combine(context, assigned);
+            if (skipLimited && !skipAssigned && pd == assigned) {
+                return acc;
+            } else if (skipAssigned && pd == context) {
+                calculateFields(acc, parent, permissions);
+                return this;
+            }
         }
 
-        // optimization: if neither have contexts; return acc if possible
-        // rather than this, because acc might have a combiner
-        if (skipAssigned && skipStack) {
-            return this;
-        }
+        // Reuse existing ACC
+        this.context = pd;
+        this.combiner = combiner;
+        this.isPrivileged = false;
 
-        // optimization: if there is no stack context; there is no reason
-        // to compress the assigned context, it already is compressed
-        if (skipStack) {
-            return acc;
-        }
+        calculateFields(acc, parent, permissions);
+        return this;
+    }
 
-        int slen = context.length;
+
+    /*
+     * Combine the current (stack) and assigned domains.
+     */
+    private static ProtectionDomain[] combine(ProtectionDomain[]current,
+        ProtectionDomain[] assigned) {
+
+        // current could be null if only system code is on the stack;
+        // in that case, ignore the stack context
+        boolean skipStack = (current == null);
+
+        // assigned could be null if only system code was involved;
+        // in that case, ignore the assigned context
+        boolean skipAssigned = (assigned == null);
+
+        int slen = (skipStack) ? 0 : current.length;
 
         // optimization: if there is no assigned context and the stack length
         // is less then or equal to two; there is no reason to compress the
         // stack context, it already is
         if (skipAssigned && slen <= 2) {
-            return this;
+            return current;
         }
 
-        // optimization: if there is a single stack domain and that domain
-        // is already in the assigned context; no need to combine
-        if ((slen == 1) && (context[0] == acc.context[0])) {
-            return acc;
-        }
-
-        int n = (skipAssigned) ? 0 : acc.context.length;
+        int n = (skipAssigned) ? 0 : assigned.length;
 
         // now we combine both of them, and create a new context
         ProtectionDomain pd[] = new ProtectionDomain[slen + n];
 
         // first copy in the assigned context domains, no need to compress
         if (!skipAssigned) {
-            System.arraycopy(acc.context, 0, pd, 0, n);
+            System.arraycopy(assigned, 0, pd, 0, n);
         }
 
         // now add the stack context domains, discarding nulls and duplicates
     outer:
-        for (int i = 0; i < context.length; i++) {
-            ProtectionDomain sd = context[i];
+        for (int i = 0; i < slen; i++) {
+            ProtectionDomain sd = current[i];
             if (sd != null) {
                 for (int j = 0; j < n; j++) {
                     if (sd == pd[j]) {
@@ -453,53 +669,47 @@
         // if length isn't equal, we need to shorten the array
         if (n != pd.length) {
             // optimization: if we didn't really combine anything
-            if (!skipAssigned && n == acc.context.length) {
-                return acc;
+            if (!skipAssigned && n == assigned.length) {
+                return assigned;
             } else if (skipAssigned && n == slen) {
-                return this;
+                return current;
             }
             ProtectionDomain tmp[] = new ProtectionDomain[n];
             System.arraycopy(pd, 0, tmp, 0, n);
             pd = tmp;
         }
 
-        //      return new AccessControlContext(pd, false);
-
-        // Reuse existing ACC
-
-        this.context = pd;
-        this.combiner = null;
-        this.isPrivileged = false;
-
-        return this;
+        return pd;
     }
 
-    private AccessControlContext goCombiner(ProtectionDomain[] current,
-                                        AccessControlContext assigned) {
 
-        // the assigned ACC's combiner is not null --
-        // let the combiner do its thing
+    /*
+     * Calculate the additional domains that could potentially be reached via
+     * limited privilege scope. Mark the context as being subject to limited
+     * privilege scope unless the reachable domains (if any) are already
+     * contained in this domain context (in which case any limited
+     * privilege scope checking would be redundant).
+     */
+    private void calculateFields(AccessControlContext assigned,
+        AccessControlContext parent, Permission[] permissions)
+    {
+        ProtectionDomain[] parentLimit = null;
+        ProtectionDomain[] assignedLimit = null;
+        ProtectionDomain[] newLimit;
 
-        // XXX we could add optimizations to 'current' here ...
+        parentLimit = (parent != null)? parent.limitedContext: null;
+        assignedLimit = (assigned != null)? assigned.limitedContext: null;
+        newLimit = combine(parentLimit, assignedLimit);
+        if (newLimit != null) {
+            if (context == null || !containsAllPDs(newLimit, context)) {
+                this.limitedContext = newLimit;
+                this.permissions = permissions;
+                this.parent = parent;
+                this.isLimited = true;
+            }
+        }
+    }
 
-        if (getDebug() != null) {
-            debug.println("AccessControlContext invoking the Combiner");
-        }
-
-        // No need to clone current and assigned.context
-        // combine() will not update them
-        ProtectionDomain[] combinedPds = assigned.combiner.combine(
-            current, assigned.context);
-
-        // return new AccessControlContext(combinedPds, assigned.combiner);
-
-        // Reuse existing ACC
-        this.context = combinedPds;
-        this.combiner = assigned.combiner;
-        this.isPrivileged = false;
-
-        return this;
-    }
 
     /**
      * Checks two AccessControlContext objects for equality.
@@ -520,31 +730,131 @@
 
         AccessControlContext that = (AccessControlContext) obj;
 
-
-        if (context == null) {
-            return (that.context == null);
-        }
-
-        if (that.context == null)
+        if (!equalContext(that))
             return false;
 
-        if (!(this.containsAllPDs(that) && that.containsAllPDs(this)))
-            return false;
-
-        if (this.combiner == null)
-            return (that.combiner == null);
-
-        if (that.combiner == null)
-            return false;
-
-        if (!this.combiner.equals(that.combiner))
+        if (!equalLimitedContext(that))
             return false;
 
         return true;
     }
 
-    private boolean containsAllPDs(AccessControlContext that) {
+    /*
+     * Compare for equality based on state that is free of limited
+     * privilege complications.
+     */
+    private boolean equalContext(AccessControlContext that) {
+        if (!equalPDs(this.context, that.context))
+            return false;
+
+        if (this.combiner == null && that.combiner != null)
+            return false;
+
+        if (this.combiner != null && !this.combiner.equals(that.combiner))
+            return false;
+
+        return true;
+    }
+
+    private boolean equalPDs(ProtectionDomain[] a, ProtectionDomain[] b) {
+        if (a == null) {
+            return (b == null);
+        }
+
+        if (b == null)
+            return false;
+
+        if (!(containsAllPDs(a, b) && containsAllPDs(b, a)))
+            return false;
+
+        return true;
+    }
+
+    /*
+     * Compare for equality based on state that is captured during a
+     * call to AccessController.getContext() when a limited privilege
+     * scope is in effect.
+     */
+    private boolean equalLimitedContext(AccessControlContext that) {
+        if (that == null)
+            return false;
+
+        /*
+         * If neither instance has limited privilege scope then we're done.
+         */
+        if (!this.isLimited && !that.isLimited)
+            return true;
+
+        /*
+         * If only one instance has limited privilege scope then we're done.
+         */
+         if (!(this.isLimited && that.isLimited))
+             return false;
+
+        /*
+         * Wrapped instances should never escape outside the implementation
+         * this class and AccessController so this will probably never happen
+         * but it only makes any sense to compare if they both have the same
+         * isWrapped state.
+         */
+        if ((this.isWrapped && !that.isWrapped) ||
+            (!this.isWrapped && that.isWrapped)) {
+            return false;
+        }
+
+        if (this.permissions == null && that.permissions != null)
+            return false;
+
+        if (this.permissions != null && that.permissions == null)
+            return false;
+
+        if (!(this.containsAllLimits(that) && that.containsAllLimits(this)))
+            return false;
+
+        /*
+         * Skip through any wrapped contexts.
+         */
+        AccessControlContext thisNextPC = getNextPC(this);
+        AccessControlContext thatNextPC = getNextPC(that);
+
+        /*
+         * The protection domains and combiner of a privilegedContext are
+         * not relevant because they have already been included in the context
+         * of this instance by optimize() so we only care about any limited
+         * privilege state they may have.
+         */
+        if (thisNextPC == null && thatNextPC != null && thatNextPC.isLimited)
+            return false;
+
+        if (thisNextPC != null && !thisNextPC.equalLimitedContext(thatNextPC))
+            return false;
+
+        if (this.parent == null && that.parent != null)
+            return false;
+
+        if (this.parent != null && !this.parent.equals(that.parent))
+            return false;
+
+        return true;
+    }
+
+    /*
+     * Follow the privilegedContext link making our best effort to skip
+     * through any wrapper contexts.
+     */
+    private static AccessControlContext getNextPC(AccessControlContext acc) {
+        while (acc != null && acc.privilegedContext != null) {
+            acc = acc.privilegedContext;
+            if (!acc.isWrapped)
+                return acc;
+        }
+        return null;
+    }
+
+    private static boolean containsAllPDs(ProtectionDomain[] thisContext,
+        ProtectionDomain[] thatContext) {
         boolean match = false;
+
         //
         // ProtectionDomains within an ACC currently cannot be null
         // and this is enforced by the constructor and the various
@@ -552,17 +862,17 @@
         // to support the notion of a null PD and therefore this logic continues
         // to support that notion.
         ProtectionDomain thisPd;
-        for (int i = 0; i < context.length; i++) {
+        for (int i = 0; i < thisContext.length; i++) {
             match = false;
-            if ((thisPd = context[i]) == null) {
-                for (int j = 0; (j < that.context.length) && !match; j++) {
-                    match = (that.context[j] == null);
+            if ((thisPd = thisContext[i]) == null) {
+                for (int j = 0; (j < thatContext.length) && !match; j++) {
+                    match = (thatContext[j] == null);
                 }
             } else {
                 Class<?> thisPdClass = thisPd.getClass();
                 ProtectionDomain thatPd;
-                for (int j = 0; (j < that.context.length) && !match; j++) {
-                    thatPd = that.context[j];
+                for (int j = 0; (j < thatContext.length) && !match; j++) {
+                    thatPd = thatContext[j];
 
                     // Class check required to avoid PD exposure (4285406)
                     match = (thatPd != null &&
@@ -573,6 +883,29 @@
         }
         return match;
     }
+
+    private boolean containsAllLimits(AccessControlContext that) {
+        boolean match = false;
+        Permission thisPerm;
+
+        if (this.permissions == null && that.permissions == null)
+            return true;
+
+        for (int i = 0; i < this.permissions.length; i++) {
+            Permission limit = this.permissions[i];
+            Class <?> limitClass = limit.getClass();
+            match = false;
+            for (int j = 0; (j < that.permissions.length) && !match; j++) {
+                Permission perm = that.permissions[j];
+                match = (limitClass.equals(perm.getClass()) &&
+                    limit.equals(perm));
+            }
+            if (!match) return false;
+        }
+        return match;
+    }
+
+
     /**
      * Returns the hash code value for this context. The hash code
      * is computed by exclusive or-ing the hash code of all the protection
@@ -591,6 +924,7 @@
             if (context[i] != null)
                 hashCode ^= context[i].hashCode();
         }
+
         return hashCode;
     }
 }
--- a/src/share/classes/java/security/AccessController.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/security/AccessController.java	Wed Jun 05 12:31:59 2013 -0700
@@ -82,9 +82,15 @@
  *     else if (caller i is marked as privileged) {
  *         if (a context was specified in the call to doPrivileged)
  *             context.checkPermission(permission)
- *         return;
+ *         if (limited permissions were specified in the call to doPrivileged) {
+ *             for (each limited permission) {
+ *                 if (the limited permission implies the requested permission)
+ *                     return;
+ *             }
+ *         } else
+ *             return;
  *     }
- * };
+ * }
  *
  * // Next, check the context inherited when the thread was created.
  * // Whenever a new thread is created, the AccessControlContext at
@@ -101,11 +107,16 @@
  * was marked as "privileged" via a <code>doPrivileged</code>
  * call without a context argument (see below for information about a
  * context argument). If that caller's domain has the
- * specified permission, no further checking is done and
+ * specified permission and at least one limiting permission argument (if any)
+ * implies the requested permission, no further checking is done and
  * <code>checkPermission</code>
  * returns quietly, indicating that the requested access is allowed.
  * If that domain does not have the specified permission, an exception
- * is thrown, as usual.
+ * is thrown, as usual. If the caller's domain had the specified permission
+ * but it was not implied by any limiting permission arguments given in the call
+ * to <code>doPrivileged</code> then the permission checking continues
+ * until there are no more callers or another <code>doPrivileged</code>
+ * call matches the requested permission and returns normally.
  *
  * <p> The normal use of the "privileged" feature is as follows. If you
  * don't need to return a value from within the "privileged" block, do
@@ -180,6 +191,9 @@
  *
  * <p> Be *very* careful in your use of the "privileged" construct, and
  * always remember to make the privileged code section as small as possible.
+ * You can pass <code>Permission</code> arguments to further limit the
+ * scope of the "privilege" (see below).
+ *
  *
  * <p> Note that <code>checkPermission</code> always performs security checks
  * within the context of the currently executing thread.
@@ -215,7 +229,9 @@
  *
  * <p> There are also times where you don't know a priori which permissions
  * to check the context against. In these cases you can use the
- * doPrivileged method that takes a context:
+ * doPrivileged method that takes a context. You can also limit the scope
+ * of the privileged code by passing additional <code>Permission</code>
+ * parameters.
  *
  *  <pre> {@code
  * somemethod() {
@@ -223,12 +239,21 @@
  *         public Object run() {
  *             // Code goes here. Any permission checks within this
  *             // run method will require that the intersection of the
- *             // callers protection domain and the snapshot's
- *             // context have the desired permission.
+ *             // caller's protection domain and the snapshot's
+ *             // context have the desired permission. If a requested
+ *             // permission is not implied by the limiting FilePermission
+ *             // argument then checking of the thread continues beyond the
+ *             // caller of doPrivileged.
  *         }
- *     }, acc);
+ *     }, acc, new FilePermission("/temp/*", read));
  *     ...normal code here...
  * }}</pre>
+ * <p> Passing a limiting <code>Permission</code> argument of an instance of
+ * <code>AllPermission</code> is equivalent to calling the equivalent
+ * <code>doPrivileged</code> method without limiting <code>Permission</code>
+ * arguments. Passing a zero length array of <code>Permission</code> disables
+ * the code privileges so that checking always continues beyond the caller of
+ * that <code>doPrivileged</code> method.
  *
  * @see AccessControlContext
  *
@@ -334,6 +359,112 @@
     public static native <T> T doPrivileged(PrivilegedAction<T> action,
                                             AccessControlContext context);
 
+
+    /**
+     * Performs the specified <code>PrivilegedAction</code> with privileges
+     * enabled and restricted by the specified
+     * <code>AccessControlContext</code> and with a privilege scope limited
+     * by specified <code>Permission</code> arguments.
+     *
+     * The action is performed with the intersection of the permissions
+     * possessed by the caller's protection domain, and those possessed
+     * by the domains represented by the specified
+     * <code>AccessControlContext</code>.
+     * <p>
+     * If the action's <code>run</code> method throws an (unchecked) exception,
+     * it will propagate through this method.
+     *
+     * @param action the action to be performed.
+     * @param context an <i>access control context</i>
+     *                representing the restriction to be applied to the
+     *                caller's domain's privileges before performing
+     *                the specified action.  If the context is
+     *                <code>null</code>,
+     *                then no additional restriction is applied.
+     * @param perms the <code>Permission</code> arguments which limit the
+     *              scope of the caller's privileges. The number of arguments
+     *              is variable.
+     *
+     * @return the value returned by the action's <code>run</code> method.
+     *
+     * @throws NullPointerException if action or perms or any element of
+     *         perms is <code>null</code>
+     *
+     * @see #doPrivileged(PrivilegedAction)
+     * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext)
+     *
+     * @since 1.8
+     */
+    @CallerSensitive
+    public static <T> T doPrivileged(PrivilegedAction<T> action,
+        AccessControlContext context, Permission... perms) {
+
+        AccessControlContext parent = getContext();
+        if (perms == null) {
+            throw new NullPointerException("null permissions parameter");
+        }
+        Class <?> caller = Reflection.getCallerClass();
+        return AccessController.doPrivileged(action, createWrapper(null,
+            caller, parent, context, perms));
+    }
+
+
+    /**
+     * Performs the specified <code>PrivilegedAction</code> with privileges
+     * enabled and restricted by the specified
+     * <code>AccessControlContext</code> and with a privilege scope limited
+     * by specified <code>Permission</code> arguments.
+     *
+     * The action is performed with the intersection of the permissions
+     * possessed by the caller's protection domain, and those possessed
+     * by the domains represented by the specified
+     * <code>AccessControlContext</code>.
+     * <p>
+     * If the action's <code>run</code> method throws an (unchecked) exception,
+     * it will propagate through this method.
+     *
+     * <p> This method preserves the current AccessControlContext's
+     * DomainCombiner (which may be null) while the action is performed.
+     *
+     * @param action the action to be performed.
+     * @param context an <i>access control context</i>
+     *                representing the restriction to be applied to the
+     *                caller's domain's privileges before performing
+     *                the specified action.  If the context is
+     *                <code>null</code>,
+     *                then no additional restriction is applied.
+     * @param perms the <code>Permission</code> arguments which limit the
+     *              scope of the caller's privileges. The number of arguments
+     *              is variable.
+     *
+     * @return the value returned by the action's <code>run</code> method.
+     *
+     * @throws NullPointerException if action or perms or any element of
+     *         perms is <code>null</code>
+     *
+     * @see #doPrivileged(PrivilegedAction)
+     * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext)
+     * @see java.security.DomainCombiner
+     *
+     * @since 1.8
+     */
+    @CallerSensitive
+    public static <T> T doPrivilegedWithCombiner(PrivilegedAction<T> action,
+        AccessControlContext context, Permission... perms) {
+
+        AccessControlContext parent = getContext();
+        DomainCombiner dc = parent.getCombiner();
+        if (dc == null && context != null) {
+            dc = context.getCombiner();
+        }
+        if (perms == null) {
+            throw new NullPointerException("null permissions parameter");
+        }
+        Class <?> caller = Reflection.getCallerClass();
+        return AccessController.doPrivileged(action, createWrapper(dc, caller,
+            parent, context, perms));
+    }
+
     /**
      * Performs the specified <code>PrivilegedExceptionAction</code> with
      * privileges enabled.  The action is performed with <i>all</i> of the
@@ -408,6 +539,22 @@
     private static AccessControlContext preserveCombiner(DomainCombiner combiner,
                                                          Class<?> caller)
     {
+        return createWrapper(combiner, caller, null, null, null);
+    }
+
+    /**
+     * Create a wrapper to contain the limited privilege scope data.
+     */
+    private static AccessControlContext
+        createWrapper(DomainCombiner combiner, Class<?> caller,
+                      AccessControlContext parent, AccessControlContext context,
+                      Permission[] perms)
+    {
+        return new AccessControlContext(getCallerPD(caller), combiner, parent,
+                                        context, perms);
+    }
+
+    private static ProtectionDomain getCallerPD(final Class <?> caller) {
         ProtectionDomain callerPd = doPrivileged
             (new PrivilegedAction<ProtectionDomain>() {
             public ProtectionDomain run() {
@@ -415,18 +562,9 @@
             }
         });
 
-        // perform 'combine' on the caller of doPrivileged,
-        // even if the caller is from the bootclasspath
-        ProtectionDomain[] pds = new ProtectionDomain[] {callerPd};
-        if (combiner == null) {
-            return new AccessControlContext(pds);
-        } else {
-            return new AccessControlContext(combiner.combine(pds, null),
-                                            combiner);
-        }
+        return callerPd;
     }
 
-
     /**
      * Performs the specified <code>PrivilegedExceptionAction</code> with
      * privileges enabled and restricted by the specified
@@ -454,7 +592,7 @@
      * @exception NullPointerException if the action is <code>null</code>
      *
      * @see #doPrivileged(PrivilegedAction)
-     * @see #doPrivileged(PrivilegedExceptionAction,AccessControlContext)
+     * @see #doPrivileged(PrivilegedAction,AccessControlContext)
      */
     @CallerSensitive
     public static native <T> T
@@ -462,6 +600,118 @@
                      AccessControlContext context)
         throws PrivilegedActionException;
 
+
+    /**
+     * Performs the specified <code>PrivilegedExceptionAction</code> with
+     * privileges enabled and restricted by the specified
+     * <code>AccessControlContext</code> and with a privilege scope limited by
+     * specified <code>Permission</code> arguments.
+     *
+     * The action is performed with the intersection of the permissions
+     * possessed by the caller's protection domain, and those possessed
+     * by the domains represented by the specified
+     * <code>AccessControlContext</code>.
+     * <p>
+     * If the action's <code>run</code> method throws an (unchecked) exception,
+     * it will propagate through this method.
+     *
+     * @param action the action to be performed.
+     * @param context an <i>access control context</i>
+     *                representing the restriction to be applied to the
+     *                caller's domain's privileges before performing
+     *                the specified action.  If the context is
+     *                <code>null</code>,
+     *                then no additional restriction is applied.
+     * @param perms the <code>Permission</code> arguments which limit the
+     *              scope of the caller's privileges. The number of arguments
+     *              is variable.
+     *
+     * @return the value returned by the action's <code>run</code> method.
+     *
+     * @throws PrivilegedActionException if the specified action's
+     *         <code>run</code> method threw a <i>checked</i> exception
+     * @throws NullPointerException if action or perms or any element of
+     *         perms is <code>null</code>
+     *
+     * @see #doPrivileged(PrivilegedAction)
+     * @see #doPrivileged(PrivilegedAction,AccessControlContext)
+     *
+     * @since 1.8
+     */
+    @CallerSensitive
+    public static <T> T doPrivileged(PrivilegedExceptionAction<T> action,
+                                     AccessControlContext context, Permission... perms)
+        throws PrivilegedActionException
+    {
+        AccessControlContext parent = getContext();
+        if (perms == null) {
+            throw new NullPointerException("null permissions parameter");
+        }
+        Class <?> caller = Reflection.getCallerClass();
+        return AccessController.doPrivileged(action, createWrapper(null, caller, parent, context, perms));
+    }
+
+
+    /**
+     * Performs the specified <code>PrivilegedExceptionAction</code> with
+     * privileges enabled and restricted by the specified
+     * <code>AccessControlContext</code> and with a privilege scope limited by
+     * specified <code>Permission</code> arguments.
+     *
+     * The action is performed with the intersection of the permissions
+     * possessed by the caller's protection domain, and those possessed
+     * by the domains represented by the specified
+     * <code>AccessControlContext</code>.
+     * <p>
+     * If the action's <code>run</code> method throws an (unchecked) exception,
+     * it will propagate through this method.
+     *
+     * <p> This method preserves the current AccessControlContext's
+     * DomainCombiner (which may be null) while the action is performed.
+     *
+     * @param action the action to be performed.
+     * @param context an <i>access control context</i>
+     *                representing the restriction to be applied to the
+     *                caller's domain's privileges before performing
+     *                the specified action.  If the context is
+     *                <code>null</code>,
+     *                then no additional restriction is applied.
+     * @param perms the <code>Permission</code> arguments which limit the
+     *              scope of the caller's privileges. The number of arguments
+     *              is variable.
+     *
+     * @return the value returned by the action's <code>run</code> method.
+     *
+     * @throws PrivilegedActionException if the specified action's
+     *         <code>run</code> method threw a <i>checked</i> exception
+     * @throws NullPointerException if action or perms or any element of
+     *         perms is <code>null</code>
+     *
+     * @see #doPrivileged(PrivilegedAction)
+     * @see #doPrivileged(PrivilegedAction,AccessControlContext)
+     * @see java.security.DomainCombiner
+     *
+     * @since 1.8
+     */
+    @CallerSensitive
+    public static <T> T doPrivilegedWithCombiner(PrivilegedExceptionAction<T> action,
+                                                 AccessControlContext context,
+                                                 Permission... perms)
+        throws PrivilegedActionException
+    {
+        AccessControlContext parent = getContext();
+        DomainCombiner dc = parent.getCombiner();
+        if (dc == null && context != null) {
+            dc = context.getCombiner();
+        }
+        if (perms == null) {
+            throw new NullPointerException("null permissions parameter");
+        }
+        Class <?> caller = Reflection.getCallerClass();
+        return AccessController.doPrivileged(action, createWrapper(dc, caller,
+            parent, context, perms));
+    }
+
     /**
      * Returns the AccessControl context. i.e., it gets
      * the protection domains of all the callers on the stack,
@@ -474,6 +724,7 @@
 
     private static native AccessControlContext getStackAccessControlContext();
 
+
     /**
      * Returns the "inherited" AccessControl context. This is the context
      * that existed when the thread was created. Package private so
@@ -484,9 +735,9 @@
 
     /**
      * This method takes a "snapshot" of the current calling context, which
-     * includes the current Thread's inherited AccessControlContext,
-     * and places it in an AccessControlContext object. This context may then
-     * be checked at a later point, possibly in another thread.
+     * includes the current Thread's inherited AccessControlContext and any
+     * limited privilege scope, and places it in an AccessControlContext object.
+     * This context may then be checked at a later point, possibly in another thread.
      *
      * @see AccessControlContext
      *
@@ -524,7 +775,7 @@
      */
 
     public static void checkPermission(Permission perm)
-                 throws AccessControlException
+        throws AccessControlException
     {
         //System.err.println("checkPermission "+perm);
         //Thread.currentThread().dumpStack();
--- a/src/share/classes/java/security/DigestOutputStream.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/security/DigestOutputStream.java	Wed Jun 05 12:31:59 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -112,10 +112,10 @@
      * @see MessageDigest#update(byte)
      */
     public void write(int b) throws IOException {
+        out.write(b);
         if (on) {
             digest.update((byte)b);
         }
-        out.write(b);
     }
 
     /**
@@ -142,10 +142,10 @@
      * @see MessageDigest#update(byte[], int, int)
      */
     public void write(byte[] b, int off, int len) throws IOException {
+        out.write(b, off, len);
         if (on) {
             digest.update(b, off, len);
         }
-        out.write(b, off, len);
     }
 
     /**
--- a/src/share/classes/java/util/HashMap.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/HashMap.java	Wed Jun 05 12:31:59 2013 -0700
@@ -26,6 +26,8 @@
 package java.util;
 
 import java.io.*;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
 import java.util.function.Consumer;
 import java.util.function.BiFunction;
 import java.util.function.Function;
@@ -126,7 +128,7 @@
  */
 
 public class HashMap<K,V>
-    extends AbstractMap<K,V>
+        extends AbstractMap<K,V>
     implements Map<K,V>, Cloneable, Serializable
 {
 
@@ -150,12 +152,12 @@
     /**
      * An empty table instance to share when the table is not inflated.
      */
-    static final Entry<?,?>[] EMPTY_TABLE = {};
+    static final Object[] EMPTY_TABLE = {};
 
     /**
      * The table, resized as necessary. Length MUST Always be a power of two.
      */
-    transient Entry<?,?>[] table = EMPTY_TABLE;
+    transient Object[] table = EMPTY_TABLE;
 
     /**
      * The number of key-value mappings contained in this map.
@@ -186,10 +188,10 @@
      */
     transient int modCount;
 
+    /**
+     * Holds values which can't be initialized until after VM is booted.
+     */
     private static class Holder {
-         /**
-         *
-         */
         static final sun.misc.Unsafe UNSAFE;
 
         /**
@@ -198,22 +200,616 @@
          */
         static final long HASHSEED_OFFSET;
 
+        static final boolean USE_HASHSEED;
+
         static {
-            try {
-                UNSAFE = sun.misc.Unsafe.getUnsafe();
-                HASHSEED_OFFSET = UNSAFE.objectFieldOffset(
-                    HashMap.class.getDeclaredField("hashSeed"));
-            } catch (NoSuchFieldException | SecurityException e) {
-                throw new InternalError("Failed to record hashSeed offset", e);
+            String hashSeedProp = java.security.AccessController.doPrivileged(
+                    new sun.security.action.GetPropertyAction(
+                        "jdk.map.useRandomSeed"));
+            boolean localBool = (null != hashSeedProp)
+                    ? Boolean.parseBoolean(hashSeedProp) : false;
+            USE_HASHSEED = localBool;
+
+            if (USE_HASHSEED) {
+                try {
+                    UNSAFE = sun.misc.Unsafe.getUnsafe();
+                    HASHSEED_OFFSET = UNSAFE.objectFieldOffset(
+                        HashMap.class.getDeclaredField("hashSeed"));
+                } catch (NoSuchFieldException | SecurityException e) {
+                    throw new InternalError("Failed to record hashSeed offset", e);
+                }
+            } else {
+                UNSAFE = null;
+                HASHSEED_OFFSET = 0;
             }
         }
     }
 
-    /**
+    /*
      * A randomizing value associated with this instance that is applied to
      * hash code of keys to make hash collisions harder to find.
+     *
+     * Non-final so it can be set lazily, but be sure not to set more than once.
      */
-    transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this);
+    transient final int hashSeed;
+
+    /*
+     * TreeBin/TreeNode code from CHM doesn't handle the null key.  Store the
+     * null key entry here.
+     */
+    transient Entry<K,V> nullKeyEntry = null;
+
+    /*
+     * In order to improve performance under high hash-collision conditions,
+     * HashMap will switch to storing a bin's entries in a balanced tree
+     * (TreeBin) instead of a linked-list once the number of entries in the bin
+     * passes a certain threshold (TreeBin.TREE_THRESHOLD), if at least one of
+     * the keys in the bin implements Comparable.  This technique is borrowed
+     * from ConcurrentHashMap.
+     */
+
+    /*
+     * Code based on CHMv8
+     *
+     * Node type for TreeBin
+     */
+    final static class TreeNode<K,V> {
+        TreeNode parent;  // red-black tree links
+        TreeNode left;
+        TreeNode right;
+        TreeNode prev;    // needed to unlink next upon deletion
+        boolean red;
+        final HashMap.Entry<K,V> entry;
+
+        TreeNode(HashMap.Entry<K,V> entry, Object next, TreeNode parent) {
+            this.entry = entry;
+            this.entry.next = next;
+            this.parent = parent;
+        }
+    }
+
+    /**
+     * Returns a Class for the given object of the form "class C
+     * implements Comparable<C>", if one exists, else null.  See the TreeBin
+     * docs, below, for explanation.
+     */
+    static Class<?> comparableClassFor(Object x) {
+        Class<?> c, s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
+        if ((c = x.getClass()) == String.class) // bypass checks
+            return c;
+        if ((cmpc = Comparable.class).isAssignableFrom(c)) {
+            while (cmpc.isAssignableFrom(s = c.getSuperclass()))
+                c = s; // find topmost comparable class
+            if ((ts  = c.getGenericInterfaces()) != null) {
+                for (int i = 0; i < ts.length; ++i) {
+                    if (((t = ts[i]) instanceof ParameterizedType) &&
+                        ((p = (ParameterizedType)t).getRawType() == cmpc) &&
+                        (as = p.getActualTypeArguments()) != null &&
+                        as.length == 1 && as[0] == c) // type arg is c
+                        return c;
+                }
+            }
+        }
+        return null;
+    }
+
+    /*
+     * Code based on CHMv8
+     *
+     * A specialized form of red-black tree for use in bins
+     * whose size exceeds a threshold.
+     *
+     * TreeBins use a special form of comparison for search and
+     * related operations (which is the main reason we cannot use
+     * existing collections such as TreeMaps). TreeBins contain
+     * Comparable elements, but may contain others, as well as
+     * elements that are Comparable but not necessarily Comparable<T>
+     * for the same T, so we cannot invoke compareTo among them. To
+     * handle this, the tree is ordered primarily by hash value, then
+     * by Comparable.compareTo order if applicable.  On lookup at a
+     * node, if elements are not comparable or compare as 0 then both
+     * left and right children may need to be searched in the case of
+     * tied hash values. (This corresponds to the full list search
+     * that would be necessary if all elements were non-Comparable and
+     * had tied hashes.)  The red-black balancing code is updated from
+     * pre-jdk-collections
+     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
+     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
+     * Algorithms" (CLR).
+     */
+    final class TreeBin {
+        /*
+         * The bin count threshold for using a tree rather than list for a bin. The
+         * value reflects the approximate break-even point for using tree-based
+         * operations.
+         */
+        static final int TREE_THRESHOLD = 16;
+
+        TreeNode<K,V> root;  // root of tree
+        TreeNode<K,V> first; // head of next-pointer list
+
+        /*
+         * Split a TreeBin into lo and hi parts and install in given table.
+         *
+         * Existing Entrys are re-used, which maintains the before/after links for
+         * LinkedHashMap.Entry.
+         *
+         * No check for Comparable, though this is the same as CHM.
+         */
+        final void splitTreeBin(Object[] newTable, int i, TreeBin loTree, TreeBin hiTree) {
+            TreeBin oldTree = this;
+            int bit = newTable.length >>> 1;
+            int loCount = 0, hiCount = 0;
+            TreeNode<K,V> e = oldTree.first;
+            TreeNode<K,V> next;
+
+            // This method is called when the table has just increased capacity,
+            // so indexFor() is now taking one additional bit of hash into
+            // account ("bit").  Entries in this TreeBin now belong in one of
+            // two bins, "i" or "i+bit", depending on if the new top bit of the
+            // hash is set.  The trees for the two bins are loTree and hiTree.
+            // If either tree ends up containing fewer than TREE_THRESHOLD
+            // entries, it is converted back to a linked list.
+            while (e != null) {
+                // Save entry.next - it will get overwritten in putTreeNode()
+                next = (TreeNode<K,V>)e.entry.next;
+
+                int h = e.entry.hash;
+                K k = (K) e.entry.key;
+                V v = e.entry.value;
+                if ((h & bit) == 0) {
+                    ++loCount;
+                    // Re-using e.entry
+                    loTree.putTreeNode(h, k, v, e.entry);
+                } else {
+                    ++hiCount;
+                    hiTree.putTreeNode(h, k, v, e.entry);
+                }
+                // Iterate using the saved 'next'
+                e = next;
+            }
+            if (loCount < TREE_THRESHOLD) { // too small, convert back to list
+                HashMap.Entry loEntry = null;
+                TreeNode<K,V> p = loTree.first;
+                while (p != null) {
+                    @SuppressWarnings("unchecked")
+                    TreeNode<K,V> savedNext = (TreeNode<K,V>) p.entry.next;
+                    p.entry.next = loEntry;
+                    loEntry = p.entry;
+                    p = savedNext;
+                }
+                // assert newTable[i] == null;
+                newTable[i] = loEntry;
+            } else {
+                // assert newTable[i] == null;
+                newTable[i] = loTree;
+            }
+            if (hiCount < TREE_THRESHOLD) { // too small, convert back to list
+                HashMap.Entry hiEntry = null;
+                TreeNode<K,V> p = hiTree.first;
+                while (p != null) {
+                    @SuppressWarnings("unchecked")
+                    TreeNode<K,V> savedNext = (TreeNode<K,V>) p.entry.next;
+                    p.entry.next = hiEntry;
+                    hiEntry = p.entry;
+                    p = savedNext;
+                }
+                // assert newTable[i + bit] == null;
+                newTable[i + bit] = hiEntry;
+            } else {
+                // assert newTable[i + bit] == null;
+                newTable[i + bit] = hiTree;
+            }
+        }
+
+        /*
+         * Popuplate the TreeBin with entries from the linked list e
+         *
+         * Assumes 'this' is a new/empty TreeBin
+         *
+         * Note: no check for Comparable
+         * Note: I believe this changes iteration order
+         */
+        @SuppressWarnings("unchecked")
+        void populate(HashMap.Entry e) {
+            // assert root == null;
+            // assert first == null;
+            HashMap.Entry next;
+            while (e != null) {
+                // Save entry.next - it will get overwritten in putTreeNode()
+                next = (HashMap.Entry)e.next;
+                // Re-using Entry e will maintain before/after in LinkedHM
+                putTreeNode(e.hash, (K)e.key, (V)e.value, e);
+                // Iterate using the saved 'next'
+                e = next;
+            }
+        }
+
+        /**
+         * Copied from CHMv8
+         * From CLR
+         */
+        private void rotateLeft(TreeNode p) {
+            if (p != null) {
+                TreeNode r = p.right, pp, rl;
+                if ((rl = p.right = r.left) != null) {
+                    rl.parent = p;
+                }
+                if ((pp = r.parent = p.parent) == null) {
+                    root = r;
+                } else if (pp.left == p) {
+                    pp.left = r;
+                } else {
+                    pp.right = r;
+                }
+                r.left = p;
+                p.parent = r;
+            }
+        }
+
+        /**
+         * Copied from CHMv8
+         * From CLR
+         */
+        private void rotateRight(TreeNode p) {
+            if (p != null) {
+                TreeNode l = p.left, pp, lr;
+                if ((lr = p.left = l.right) != null) {
+                    lr.parent = p;
+                }
+                if ((pp = l.parent = p.parent) == null) {
+                    root = l;
+                } else if (pp.right == p) {
+                    pp.right = l;
+                } else {
+                    pp.left = l;
+                }
+                l.right = p;
+                p.parent = l;
+            }
+        }
+
+        /**
+         * Returns the TreeNode (or null if not found) for the given
+         * key.  A front-end for recursive version.
+         */
+        final TreeNode getTreeNode(int h, K k) {
+            return getTreeNode(h, k, root, comparableClassFor(k));
+        }
+
+        /**
+         * Returns the TreeNode (or null if not found) for the given key
+         * starting at given root.
+         */
+        @SuppressWarnings("unchecked")
+        final TreeNode getTreeNode (int h, K k, TreeNode p, Class<?> cc) {
+            // assert k != null;
+            while (p != null) {
+                int dir, ph;  Object pk;
+                if ((ph = p.entry.hash) != h)
+                    dir = (h < ph) ? -1 : 1;
+                else if ((pk = p.entry.key) == k || k.equals(pk))
+                    return p;
+                else if (cc == null || comparableClassFor(pk) != cc ||
+                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
+                    // assert pk != null;
+                    TreeNode r, pl, pr; // check both sides
+                    if ((pr = p.right) != null &&
+                        (r = getTreeNode(h, k, pr, cc)) != null)
+                        return r;
+                    else if ((pl = p.left) != null)
+                        dir = -1;
+                    else // nothing there
+                        break;
+                }
+                p = (dir > 0) ? p.right : p.left;
+            }
+            return null;
+        }
+
+        /*
+         * Finds or adds a node.
+         *
+         * 'entry' should be used to recycle an existing Entry (e.g. in the case
+         * of converting a linked-list bin to a TreeBin).
+         * If entry is null, a new Entry will be created for the new TreeNode
+         *
+         * @return the TreeNode containing the mapping, or null if a new
+         * TreeNode was added
+         */
+        @SuppressWarnings("unchecked")
+        TreeNode putTreeNode(int h, K k, V v, HashMap.Entry<K,V> entry) {
+            // assert k != null;
+            //if (entry != null) {
+                // assert h == entry.hash;
+                // assert k == entry.key;
+                // assert v == entry.value;
+            // }
+            Class<?> cc = comparableClassFor(k);
+            TreeNode pp = root, p = null;
+            int dir = 0;
+            while (pp != null) { // find existing node or leaf to insert at
+                int ph;  Object pk;
+                p = pp;
+                if ((ph = p.entry.hash) != h)
+                    dir = (h < ph) ? -1 : 1;
+                else if ((pk = p.entry.key) == k || k.equals(pk))
+                    return p;
+                else if (cc == null || comparableClassFor(pk) != cc ||
+                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
+                    TreeNode r, pr;
+                    if ((pr = p.right) != null &&
+                        (r = getTreeNode(h, k, pr, cc)) != null)
+                        return r;
+                    else // continue left
+                        dir = -1;
+                }
+                pp = (dir > 0) ? p.right : p.left;
+            }
+
+            // Didn't find the mapping in the tree, so add it
+            TreeNode f = first;
+            TreeNode x;
+            if (entry != null) {
+                x = new TreeNode(entry, f, p);
+            } else {
+                x = new TreeNode(newEntry(h, k, v, null), f, p);
+            }
+            first = x;
+
+            if (p == null) {
+                root = x;
+            } else { // attach and rebalance; adapted from CLR
+                TreeNode xp, xpp;
+                if (f != null) {
+                    f.prev = x;
+                }
+                if (dir <= 0) {
+                    p.left = x;
+                } else {
+                    p.right = x;
+                }
+                x.red = true;
+                while (x != null && (xp = x.parent) != null && xp.red
+                        && (xpp = xp.parent) != null) {
+                    TreeNode xppl = xpp.left;
+                    if (xp == xppl) {
+                        TreeNode y = xpp.right;
+                        if (y != null && y.red) {
+                            y.red = false;
+                            xp.red = false;
+                            xpp.red = true;
+                            x = xpp;
+                        } else {
+                            if (x == xp.right) {
+                                rotateLeft(x = xp);
+                                xpp = (xp = x.parent) == null ? null : xp.parent;
+                            }
+                            if (xp != null) {
+                                xp.red = false;
+                                if (xpp != null) {
+                                    xpp.red = true;
+                                    rotateRight(xpp);
+                                }
+                            }
+                        }
+                    } else {
+                        TreeNode y = xppl;
+                        if (y != null && y.red) {
+                            y.red = false;
+                            xp.red = false;
+                            xpp.red = true;
+                            x = xpp;
+                        } else {
+                            if (x == xp.left) {
+                                rotateRight(x = xp);
+                                xpp = (xp = x.parent) == null ? null : xp.parent;
+                            }
+                            if (xp != null) {
+                                xp.red = false;
+                                if (xpp != null) {
+                                    xpp.red = true;
+                                    rotateLeft(xpp);
+                                }
+                            }
+                        }
+                    }
+                }
+                TreeNode r = root;
+                if (r != null && r.red) {
+                    r.red = false;
+                }
+            }
+            return null;
+        }
+
+        /*
+         * From CHMv8
+         *
+         * 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.
+         */
+        final void deleteTreeNode(TreeNode p) {
+            TreeNode next = (TreeNode) p.entry.next; // unlink traversal pointers
+            TreeNode pred = p.prev;
+            if (pred == null) {
+                first = next;
+            } else {
+                pred.entry.next = next;
+            }
+            if (next != null) {
+                next.prev = pred;
+            }
+            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) {
+                    root = s;
+                } else if (p == pp.left) {
+                    pp.left = s;
+                } else {
+                    pp.right = s;
+                }
+                replacement = sr;
+            } else {
+                replacement = (pl != null) ? pl : pr;
+            }
+            TreeNode pp = p.parent;
+            if (replacement == null) {
+                if (pp == null) {
+                    root = null;
+                    return;
+                }
+                replacement = p;
+            } else {
+                replacement.parent = pp;
+                if (pp == null) {
+                    root = replacement;
+                } else if (p == pp.left) {
+                    pp.left = replacement;
+                } else {
+                    pp.right = replacement;
+                }
+                p.left = p.right = p.parent = null;
+            }
+            if (!p.red) { // rebalance, from CLR
+                TreeNode x = replacement;
+                while (x != null) {
+                    TreeNode xp, xpl;
+                    if (x.red || (xp = x.parent) == null) {
+                        x.red = false;
+                        break;
+                    }
+                    if (x == (xpl = xp.left)) {
+                        TreeNode sib = xp.right;
+                        if (sib != null && sib.red) {
+                            sib.red = false;
+                            xp.red = true;
+                            rotateLeft(xp);
+                            sib = (xp = x.parent) == null ? null : xp.right;
+                        }
+                        if (sib == null) {
+                            x = xp;
+                        } else {
+                            TreeNode sl = sib.left, sr = sib.right;
+                            if ((sr == null || !sr.red)
+                                    && (sl == null || !sl.red)) {
+                                sib.red = true;
+                                x = xp;
+                            } else {
+                                if (sr == null || !sr.red) {
+                                    if (sl != null) {
+                                        sl.red = false;
+                                    }
+                                    sib.red = true;
+                                    rotateRight(sib);
+                                    sib = (xp = x.parent) == null ?
+                                        null : xp.right;
+                                }
+                                if (sib != null) {
+                                    sib.red = (xp == null) ? false : xp.red;
+                                    if ((sr = sib.right) != null) {
+                                        sr.red = false;
+                                    }
+                                }
+                                if (xp != null) {
+                                    xp.red = false;
+                                    rotateLeft(xp);
+                                }
+                                x = root;
+                            }
+                        }
+                    } else { // symmetric
+                        TreeNode sib = xpl;
+                        if (sib != null && sib.red) {
+                            sib.red = false;
+                            xp.red = true;
+                            rotateRight(xp);
+                            sib = (xp = x.parent) == null ? null : xp.left;
+                        }
+                        if (sib == null) {
+                            x = xp;
+                        } else {
+                            TreeNode sl = sib.left, sr = sib.right;
+                            if ((sl == null || !sl.red)
+                                    && (sr == null || !sr.red)) {
+                                sib.red = true;
+                                x = xp;
+                            } else {
+                                if (sl == null || !sl.red) {
+                                    if (sr != null) {
+                                        sr.red = false;
+                                    }
+                                    sib.red = true;
+                                    rotateLeft(sib);
+                                    sib = (xp = x.parent) == null ?
+                                        null : xp.left;
+                                }
+                                if (sib != null) {
+                                    sib.red = (xp == null) ? false : xp.red;
+                                    if ((sl = sib.left) != null) {
+                                        sl.red = false;
+                                    }
+                                }
+                                if (xp != null) {
+                                    xp.red = false;
+                                    rotateRight(xp);
+                                }
+                                x = root;
+                            }
+                        }
+                    }
+                }
+            }
+            if (p == replacement && (pp = p.parent) != null) {
+                if (p == pp.left) // detach pointers
+                {
+                    pp.left = null;
+                } else if (p == pp.right) {
+                    pp.right = null;
+                }
+                p.parent = null;
+            }
+        }
+    }
 
     /**
      * Constructs an empty <tt>HashMap</tt> with the specified initial
@@ -233,9 +829,9 @@
         if (loadFactor <= 0 || Float.isNaN(loadFactor))
             throw new IllegalArgumentException("Illegal load factor: " +
                                                loadFactor);
-
         this.loadFactor = loadFactor;
         threshold = initialCapacity;
+        hashSeed = initHashSeed();
         init();
     }
 
@@ -269,10 +865,11 @@
      */
     public HashMap(Map<? extends K, ? extends V> m) {
         this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
-                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
+                DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
         inflateTable(threshold);
 
         putAllForCreate(m);
+        // assert size == m.size();
     }
 
     private static int roundUpToPowerOf2(int number) {
@@ -294,7 +891,7 @@
         int capacity = roundUpToPowerOf2(toSize);
 
         threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
-        table = new Entry[capacity];
+        table = new Object[capacity];
     }
 
     // internal utilities
@@ -310,17 +907,24 @@
     }
 
     /**
+     * Return an initial value for the hashSeed, or 0 if the random seed is not
+     * enabled.
+     */
+    final int initHashSeed() {
+        if (sun.misc.VM.isBooted() && Holder.USE_HASHSEED) {
+            return sun.misc.Hashing.randomHashSeed(this);
+        }
+        return 0;
+    }
+
+    /**
      * Retrieve object hash code and applies a supplemental hash function to the
-     * result hash, which defends against poor quality hash functions.  This is
+     * result hash, which defends against poor quality hash functions. This is
      * critical because HashMap uses power-of-two length hash tables, that
      * otherwise encounter collisions for hashCodes that do not differ
      * in lower bits.
      */
     final int hash(Object k) {
-        if (k instanceof String) {
-            return ((String) k).hash32();
-        }
-
         int  h = hashSeed ^ k.hashCode();
 
         // This function ensures that hashCodes that differ only by
@@ -409,19 +1013,35 @@
         if (isEmpty()) {
             return null;
         }
+        if (key == null) {
+            return nullKeyEntry;
+        }
+        int hash = hash(key);
+        int bin = indexFor(hash, table.length);
 
-        int hash = (key == null) ? 0 : hash(key);
-        for (Entry<?,?> e = table[indexFor(hash, table.length)];
-             e != null;
-             e = e.next) {
-            Object k;
-            if (e.hash == hash &&
-                ((k = e.key) == key || (key != null && key.equals(k))))
-                return (Entry<K,V>)e;
+        if (table[bin] instanceof Entry) {
+            Entry<K,V> e = (Entry<K,V>) table[bin];
+            for (; e != null; e = (Entry<K,V>)e.next) {
+                Object k;
+                if (e.hash == hash &&
+                    ((k = e.key) == key || key.equals(k))) {
+                    return e;
+                }
+            }
+        } else if (table[bin] != null) {
+            TreeBin e = (TreeBin)table[bin];
+            TreeNode p = e.getTreeNode(hash, (K)key);
+            if (p != null) {
+                // assert p.entry.hash == hash && p.entry.key.equals(key);
+                return (Entry<K,V>)p.entry;
+            } else {
+                return null;
+            }
         }
         return null;
     }
 
+
     /**
      * Associates the specified value with the specified key in this map.
      * If the map previously contained a mapping for the key, the old
@@ -434,28 +1054,57 @@
      *         (A <tt>null</tt> return can also indicate that the map
      *         previously associated <tt>null</tt> with <tt>key</tt>.)
      */
+    @SuppressWarnings("unchecked")
     public V put(K key, V value) {
         if (table == EMPTY_TABLE) {
             inflateTable(threshold);
         }
-        if (key == null)
+       if (key == null)
             return putForNullKey(value);
         int hash = hash(key);
         int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-        Entry<K,V> e = (Entry<K,V>)table[i];
-        for(; e != null; e = e.next) {
-            Object k;
-            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
-                V oldValue = e.value;
-                e.value = value;
-                e.recordAccess(this);
-                return oldValue;
+        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
+
+        if (table[i] instanceof Entry) {
+            // Bin contains ordinary Entries.  Search for key in the linked list
+            // of entries, counting the number of entries.  Only check for
+            // TreeBin conversion if the list size is >= TREE_THRESHOLD.
+            // (The conversion still may not happen if the table gets resized.)
+            int listSize = 0;
+            Entry<K,V> e = (Entry<K,V>) table[i];
+            for (; e != null; e = (Entry<K,V>)e.next) {
+                Object k;
+                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
+                    V oldValue = e.value;
+                    e.value = value;
+                    e.recordAccess(this);
+                    return oldValue;
+                }
+                listSize++;
+            }
+            // Didn't find, so fall through and call addEntry() to add the
+            // Entry and check for TreeBin conversion.
+            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
+        } else if (table[i] != null) {
+            TreeBin e = (TreeBin)table[i];
+            TreeNode p = e.putTreeNode(hash, key, value, null);
+            if (p == null) { // putTreeNode() added a new node
+                modCount++;
+                size++;
+                if (size >= threshold) {
+                    resize(2 * table.length);
+                }
+                return null;
+            } else { // putTreeNode() found an existing node
+                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                V oldVal = pEntry.value;
+                pEntry.value = value;
+                pEntry.recordAccess(this);
+                return oldVal;
             }
         }
-
         modCount++;
-        addEntry(hash, key, value, i);
+        addEntry(hash, key, value, i, checkIfNeedTree);
         return null;
     }
 
@@ -463,47 +1112,79 @@
      * Offloaded version of put for null keys
      */
     private V putForNullKey(V value) {
-        @SuppressWarnings("unchecked")
-        Entry<K,V> e = (Entry<K,V>)table[0];
-        for(; e != null; e = e.next) {
-            if (e.key == null) {
-                V oldValue = e.value;
-                e.value = value;
-                e.recordAccess(this);
-                return oldValue;
-            }
+        if (nullKeyEntry != null) {
+            V oldValue = nullKeyEntry.value;
+            nullKeyEntry.value = value;
+            nullKeyEntry.recordAccess(this);
+            return oldValue;
         }
         modCount++;
-        addEntry(0, null, value, 0);
+        size++; // newEntry() skips size++
+        nullKeyEntry = newEntry(0, null, value, null);
         return null;
     }
 
+    private void putForCreateNullKey(V value) {
+        // Look for preexisting entry for key.  This will never happen for
+        // clone or deserialize.  It will only happen for construction if the
+        // input Map is a sorted map whose ordering is inconsistent w/ equals.
+        if (nullKeyEntry != null) {
+            nullKeyEntry.value = value;
+        } else {
+            nullKeyEntry = newEntry(0, null, value, null);
+            size++;
+        }
+    }
+
+
     /**
      * This method is used instead of put by constructors and
      * pseudoconstructors (clone, readObject).  It does not resize the table,
-     * check for comodification, etc.  It calls createEntry rather than
-     * addEntry.
+     * check for comodification, etc, though it will convert bins to TreeBins
+     * as needed.  It calls createEntry rather than addEntry.
      */
+    @SuppressWarnings("unchecked")
     private void putForCreate(K key, V value) {
-        int hash = null == key ? 0 : hash(key);
+        if (null == key) {
+            putForCreateNullKey(value);
+            return;
+        }
+        int hash = hash(key);
         int i = indexFor(hash, table.length);
+        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
 
         /**
          * Look for preexisting entry for key.  This will never happen for
          * clone or deserialize.  It will only happen for construction if the
          * input Map is a sorted map whose ordering is inconsistent w/ equals.
          */
-        for (@SuppressWarnings("unchecked")
-             Entry<?,V> e = (Entry<?,V>)table[i]; e != null; e = e.next) {
-            Object k;
-            if (e.hash == hash &&
-                ((k = e.key) == key || (key != null && key.equals(k)))) {
-                e.value = value;
-                return;
+        if (table[i] instanceof Entry) {
+            int listSize = 0;
+            Entry<K,V> e = (Entry<K,V>) table[i];
+            for (; e != null; e = (Entry<K,V>)e.next) {
+                Object k;
+                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
+                    e.value = value;
+                    return;
+                }
+                listSize++;
             }
+            // Didn't find, fall through to createEntry().
+            // Check for conversion to TreeBin done via createEntry().
+            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
+        } else if (table[i] != null) {
+            TreeBin e = (TreeBin)table[i];
+            TreeNode p = e.putTreeNode(hash, key, value, null);
+            if (p != null) {
+                p.entry.setValue(value); // Found an existing node, set value
+            } else {
+                size++; // Added a new TreeNode, so update size
+            }
+            // don't need modCount++/check for resize - just return
+            return;
         }
 
-        createEntry(hash, key, value, i);
+        createEntry(hash, key, value, i, checkIfNeedTree);
     }
 
     private void putAllForCreate(Map<? extends K, ? extends V> m) {
@@ -526,14 +1207,14 @@
      *        is irrelevant).
      */
     void resize(int newCapacity) {
-        Entry<?,?>[] oldTable = table;
+        Object[] oldTable = table;
         int oldCapacity = oldTable.length;
         if (oldCapacity == MAXIMUM_CAPACITY) {
             threshold = Integer.MAX_VALUE;
             return;
         }
 
-        Entry<?,?>[] newTable = new Entry<?,?>[newCapacity];
+        Object[] newTable = new Object[newCapacity];
         transfer(newTable);
         table = newTable;
         threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
@@ -541,19 +1222,31 @@
 
     /**
      * Transfers all entries from current table to newTable.
+     *
+     * Assumes newTable is larger than table
      */
     @SuppressWarnings("unchecked")
-    void transfer(Entry<?,?>[] newTable) {
-        Entry<?,?>[] src = table;
+    void transfer(Object[] newTable) {
+        Object[] src = table;
+        // assert newTable.length > src.length : "newTable.length(" +
+        //   newTable.length + ") expected to be > src.length("+src.length+")";
         int newCapacity = newTable.length;
-        for (int j = 0; j < src.length; j++ ) {
-            Entry<K,V> e = (Entry<K,V>) src[j];
-            while(null != e) {
-                Entry<K,V> next = e.next;
-                int i = indexFor(e.hash, newCapacity);
-                e.next = (Entry<K,V>) newTable[i];
-                newTable[i] = e;
-                e = next;
+        for (int j = 0; j < src.length; j++) {
+             if (src[j] instanceof Entry) {
+                // Assume: since wasn't TreeBin before, won't need TreeBin now
+                Entry<K,V> e = (Entry<K,V>) src[j];
+                while (null != e) {
+                    Entry<K,V> next = (Entry<K,V>)e.next;
+                    int i = indexFor(e.hash, newCapacity);
+                    e.next = (Entry<K,V>) newTable[i];
+                    newTable[i] = e;
+                    e = next;
+                }
+            } else if (src[j] != null) {
+                TreeBin e = (TreeBin) src[j];
+                TreeBin loTree = new TreeBin();
+                TreeBin hiTree = new TreeBin();
+                e.splitTreeBin(newTable, j, loTree, hiTree);
             }
         }
         Arrays.fill(table, null);
@@ -585,20 +1278,13 @@
          * By using the conservative calculation, we subject ourself
          * to at most one extra resize.
          */
-        if (numKeysToBeAdded > threshold) {
-            int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
-            if (targetCapacity > MAXIMUM_CAPACITY)
-                targetCapacity = MAXIMUM_CAPACITY;
-            int newCapacity = table.length;
-            while (newCapacity < targetCapacity)
-                newCapacity <<= 1;
-            if (newCapacity > table.length)
-                resize(newCapacity);
+        if (numKeysToBeAdded > threshold && table.length < MAXIMUM_CAPACITY) {
+            resize(table.length * 2);
         }
 
         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
             put(e.getKey(), e.getValue());
-    }
+        }
 
     /**
      * Removes the mapping for the specified key from this map if present.
@@ -621,24 +1307,57 @@
         if (table == EMPTY_TABLE) {
             inflateTable(threshold);
         }
-        int hash = (key == null) ? 0 : hash(key);
-        int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-        Entry<K,V> e = (Entry<K,V>)table[i];
-        for(; e != null; e = e.next) {
-            if (e.hash == hash && Objects.equals(e.key, key)) {
-                if(e.value != null) {
-                    return e.value;
-                }
-                e.value = value;
-                modCount++;
-                e.recordAccess(this);
+        if (key == null) {
+            if (nullKeyEntry == null || nullKeyEntry.value == null) {
+                putForNullKey(value);
                 return null;
+            } else {
+                return nullKeyEntry.value;
             }
         }
+        int hash = hash(key);
+        int i = indexFor(hash, table.length);
+        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
 
+        if (table[i] instanceof Entry) {
+            int listSize = 0;
+            Entry<K,V> e = (Entry<K,V>) table[i];
+            for (; e != null; e = (Entry<K,V>)e.next) {
+                if (e.hash == hash && Objects.equals(e.key, key)) {
+                    if (e.value != null) {
+                        return e.value;
+                    }
+                    e.value = value;
+                    e.recordAccess(this);
+                    return null;
+                }
+                listSize++;
+            }
+            // Didn't find, so fall through and call addEntry() to add the
+            // Entry and check for TreeBin conversion.
+            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
+        } else if (table[i] != null) {
+            TreeBin e = (TreeBin)table[i];
+            TreeNode p = e.putTreeNode(hash, key, value, null);
+            if (p == null) { // not found, putTreeNode() added a new node
+                modCount++;
+                size++;
+                if (size >= threshold) {
+                    resize(2 * table.length);
+                }
+                return null;
+            } else { // putTreeNode() found an existing node
+                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                V oldVal = pEntry.value;
+                if (oldVal == null) { // only replace if maps to null
+                    pEntry.value = value;
+                    pEntry.recordAccess(this);
+                }
+                return oldVal;
+            }
+        }
         modCount++;
-        addEntry(hash, key, value, i);
+        addEntry(hash, key, value, i, checkIfNeedTree);
         return null;
     }
 
@@ -647,31 +1366,61 @@
         if (isEmpty()) {
             return false;
         }
-        int hash = (key == null) ? 0 : hash(key);
-        int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-        Entry<K,V> prev = (Entry<K,V>)table[i];
-        Entry<K,V> e = prev;
-
-        while (e != null) {
-            Entry<K,V> next = e.next;
-            if (e.hash == hash && Objects.equals(e.key, key)) {
-                if (!Objects.equals(e.value, value)) {
-                    return false;
-                }
-                modCount++;
-                size--;
-                if (prev == e)
-                    table[i] = next;
-                else
-                    prev.next = next;
-                e.recordRemoval(this);
+        if (key == null) {
+            if (nullKeyEntry != null &&
+                 Objects.equals(nullKeyEntry.value, value)) {
+                removeNullKey();
                 return true;
             }
-            prev = e;
-            e = next;
+            return false;
         }
+        int hash = hash(key);
+        int i = indexFor(hash, table.length);
 
+        if (table[i] instanceof Entry) {
+            @SuppressWarnings("unchecked")
+            Entry<K,V> prev = (Entry<K,V>) table[i];
+            Entry<K,V> e = prev;
+            while (e != null) {
+                @SuppressWarnings("unchecked")
+                Entry<K,V> next = (Entry<K,V>) e.next;
+                if (e.hash == hash && Objects.equals(e.key, key)) {
+                    if (!Objects.equals(e.value, value)) {
+                        return false;
+                    }
+                    modCount++;
+                    size--;
+                    if (prev == e)
+                        table[i] = next;
+                    else
+                        prev.next = next;
+                    e.recordRemoval(this);
+                    return true;
+                }
+                prev = e;
+                e = next;
+            }
+        } else if (table[i] != null) {
+            TreeBin tb = ((TreeBin) table[i]);
+            TreeNode p = tb.getTreeNode(hash, (K)key);
+            if (p != null) {
+                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                // assert pEntry.key.equals(key);
+                if (Objects.equals(pEntry.value, value)) {
+                    modCount++;
+                    size--;
+                    tb.deleteTreeNode(p);
+                    pEntry.recordRemoval(this);
+                    if (tb.root == null || tb.first == null) {
+                        // assert tb.root == null && tb.first == null :
+                        //         "TreeBin.first and root should both be null";
+                        // TreeBin is now empty, we should blank this bin
+                        table[i] = null;
+                    }
+                    return true;
+                }
+            }
+        }
         return false;
     }
 
@@ -680,39 +1429,82 @@
         if (isEmpty()) {
             return false;
         }
-        int hash = (key == null) ? 0 : hash(key);
-        int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-        Entry<K,V> e = (Entry<K,V>)table[i];
-        for (; e != null; e = e.next) {
-            if (e.hash == hash && Objects.equals(e.key, key) && Objects.equals(e.value, oldValue)) {
-                e.value = newValue;
-                e.recordAccess(this);
+        if (key == null) {
+            if (nullKeyEntry != null &&
+                 Objects.equals(nullKeyEntry.value, oldValue)) {
+                putForNullKey(newValue);
                 return true;
             }
+            return false;
         }
+        int hash = hash(key);
+        int i = indexFor(hash, table.length);
 
+        if (table[i] instanceof Entry) {
+            @SuppressWarnings("unchecked")
+            Entry<K,V> e = (Entry<K,V>) table[i];
+            for (; e != null; e = (Entry<K,V>)e.next) {
+                if (e.hash == hash && Objects.equals(e.key, key) && Objects.equals(e.value, oldValue)) {
+                    e.value = newValue;
+                    e.recordAccess(this);
+                    return true;
+                }
+            }
+            return false;
+        } else if (table[i] != null) {
+            TreeBin tb = ((TreeBin) table[i]);
+            TreeNode p = tb.getTreeNode(hash, key);
+            if (p != null) {
+                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                // assert pEntry.key.equals(key);
+                if (Objects.equals(pEntry.value, oldValue)) {
+                    pEntry.value = newValue;
+                    pEntry.recordAccess(this);
+                    return true;
+                }
+            }
+        }
         return false;
     }
 
-    @Override
+   @Override
     public V replace(K key, V value) {
         if (isEmpty()) {
             return null;
         }
-        int hash = (key == null) ? 0 : hash(key);
+        if (key == null) {
+            if (nullKeyEntry != null) {
+                return putForNullKey(value);
+            }
+            return null;
+        }
+        int hash = hash(key);
         int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-        Entry<K,V> e = (Entry<K,V>)table[i];
-        for (; e != null; e = e.next) {
-            if (e.hash == hash && Objects.equals(e.key, key)) {
-                V oldValue = e.value;
-                e.value = value;
-                e.recordAccess(this);
+        if (table[i] instanceof Entry) {
+            @SuppressWarnings("unchecked")
+            Entry<K,V> e = (Entry<K,V>)table[i];
+            for (; e != null; e = (Entry<K,V>)e.next) {
+                if (e.hash == hash && Objects.equals(e.key, key)) {
+                    V oldValue = e.value;
+                    e.value = value;
+                    e.recordAccess(this);
+                    return oldValue;
+                }
+            }
+
+            return null;
+        } else if (table[i] != null) {
+            TreeBin tb = ((TreeBin) table[i]);
+            TreeNode p = tb.getTreeNode(hash, key);
+            if (p != null) {
+                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                // assert pEntry.key.equals(key);
+                V oldValue = pEntry.value;
+                pEntry.value = value;
+                pEntry.recordAccess(this);
                 return oldValue;
             }
         }
-
         return null;
     }
 
@@ -721,21 +1513,75 @@
         if (table == EMPTY_TABLE) {
             inflateTable(threshold);
         }
-        int hash = (key == null) ? 0 : hash(key);
+        if (key == null) {
+            if (nullKeyEntry == null || nullKeyEntry.value == null) {
+                V newValue = mappingFunction.apply(key);
+                if (newValue != null) {
+                    putForNullKey(newValue);
+                }
+                return newValue;
+            }
+            return nullKeyEntry.value;
+        }
+        int hash = hash(key);
         int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-        Entry<K,V> e = (Entry<K,V>)table[i];
-        for (; e != null; e = e.next) {
-            if (e.hash == hash && Objects.equals(e.key, key)) {
-                V oldValue = e.value;
-                return oldValue == null ? (e.value = mappingFunction.apply(key)) : oldValue;
+        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
+
+        if (table[i] instanceof Entry) {
+            int listSize = 0;
+            @SuppressWarnings("unchecked")
+            Entry<K,V> e = (Entry<K,V>)table[i];
+            for (; e != null; e = (Entry<K,V>)e.next) {
+                if (e.hash == hash && Objects.equals(e.key, key)) {
+                    V oldValue = e.value;
+                    if (oldValue == null) {
+                        V newValue = mappingFunction.apply(key);
+                        if (newValue != null) {
+                            e.value = newValue;
+                            e.recordAccess(this);
+                        }
+                        return newValue;
+                    }
+                    return oldValue;
+                }
+                listSize++;
+            }
+            // Didn't find, fall through to call the mapping function
+            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
+        } else if (table[i] != null) {
+            TreeBin e = (TreeBin)table[i];
+            V value = mappingFunction.apply(key);
+            if (value == null) { // Return the existing value, if any
+                TreeNode p = e.getTreeNode(hash, key);
+                if (p != null) {
+                    return (V) p.entry.value;
+                }
+                return null;
+            } else { // Put the new value into the Tree, if absent
+                TreeNode p = e.putTreeNode(hash, key, value, null);
+                if (p == null) { // not found, new node was added
+                    modCount++;
+                    size++;
+                    if (size >= threshold) {
+                        resize(2 * table.length);
+                    }
+                    return value;
+                } else { // putTreeNode() found an existing node
+                    Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                    V oldVal = pEntry.value;
+                    if (oldVal == null) { // only replace if maps to null
+                        pEntry.value = value;
+                        pEntry.recordAccess(this);
+                        return value;
+                    }
+                    return oldVal;
+                }
             }
         }
-
         V newValue = mappingFunction.apply(key);
-        if (newValue != null) {
+        if (newValue != null) { // add Entry and check for TreeBin conversion
             modCount++;
-            addEntry(hash, key, newValue, i);
+            addEntry(hash, key, newValue, i, checkIfNeedTree);
         }
 
         return newValue;
@@ -746,59 +1592,34 @@
         if (isEmpty()) {
             return null;
         }
-        int hash = (key == null) ? 0 : hash(key);
+        if (key == null) {
+            V oldValue;
+            if (nullKeyEntry != null && (oldValue = nullKeyEntry.value) != null) {
+                V newValue = remappingFunction.apply(key, oldValue);
+                if (newValue != null ) {
+                    putForNullKey(newValue);
+                    return newValue;
+                } else {
+                    removeNullKey();
+                }
+            }
+            return null;
+        }
+        int hash = hash(key);
         int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-        Entry<K,V> prev = (Entry<K,V>)table[i];
-        Entry<K,V> e = prev;
-
-        while (e != null) {
-            Entry<K,V> next = e.next;
-            if (e.hash == hash && Objects.equals(e.key, key)) {
-                V oldValue = e.value;
-                if (oldValue == null)
-                    break;
-                V newValue = remappingFunction.apply(key, oldValue);
-                modCount++;
-                if (newValue == null) {
-                    size--;
-                    if (prev == e)
-                        table[i] = next;
-                    else
-                        prev.next = next;
-                    e.recordRemoval(this);
-                } else {
-                    e.value = newValue;
-                    e.recordAccess(this);
-                }
-                return newValue;
-            }
-            prev = e;
-            e = next;
-        }
-
-        return null;
-    }
-
-    @Override
-    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
-        if (table == EMPTY_TABLE) {
-            inflateTable(threshold);
-        }
-        int hash = (key == null) ? 0 : hash(key);
-        int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-        Entry<K,V> prev = (Entry<K,V>)table[i];
-        Entry<K,V> e = prev;
-
-        while (e != null) {
-            Entry<K,V> next = e.next;
-            if (e.hash == hash && Objects.equals(e.key, key)) {
-                V oldValue = e.value;
-                V newValue = remappingFunction.apply(key, oldValue);
-                if (newValue != oldValue) {
-                    modCount++;
+        if (table[i] instanceof Entry) {
+            @SuppressWarnings("unchecked")
+            Entry<K,V> prev = (Entry<K,V>)table[i];
+            Entry<K,V> e = prev;
+            while (e != null) {
+                Entry<K,V> next = (Entry<K,V>)e.next;
+                if (e.hash == hash && Objects.equals(e.key, key)) {
+                    V oldValue = e.value;
+                    if (oldValue == null)
+                        break;
+                    V newValue = remappingFunction.apply(key, oldValue);
                     if (newValue == null) {
+                        modCount++;
                         size--;
                         if (prev == e)
                             table[i] = next;
@@ -809,17 +1630,136 @@
                         e.value = newValue;
                         e.recordAccess(this);
                     }
+                    return newValue;
                 }
-                return newValue;
+                prev = e;
+                e = next;
             }
-            prev = e;
-            e = next;
+        } else if (table[i] != null) {
+            TreeBin tb = (TreeBin)table[i];
+            TreeNode p = tb.getTreeNode(hash, key);
+            if (p != null) {
+                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                // assert pEntry.key.equals(key);
+                V oldValue = pEntry.value;
+                if (oldValue != null) {
+                    V newValue = remappingFunction.apply(key, oldValue);
+                    if (newValue == null) { // remove mapping
+                        modCount++;
+                        size--;
+                        tb.deleteTreeNode(p);
+                        pEntry.recordRemoval(this);
+                        if (tb.root == null || tb.first == null) {
+                            // assert tb.root == null && tb.first == null :
+                            //     "TreeBin.first and root should both be null";
+                            // TreeBin is now empty, we should blank this bin
+                            table[i] = null;
+                        }
+                    } else {
+                        pEntry.value = newValue;
+                        pEntry.recordAccess(this);
+                    }
+                    return newValue;
+                }
+            }
+        }
+        return null;
+    }
+
+    @Override
+    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
+        if (table == EMPTY_TABLE) {
+            inflateTable(threshold);
+        }
+        if (key == null) {
+            V oldValue = nullKeyEntry == null ? null : nullKeyEntry.value;
+            V newValue = remappingFunction.apply(key, oldValue);
+            if (newValue != oldValue) {
+                if (newValue == null) {
+                    removeNullKey();
+                } else {
+                    putForNullKey(newValue);
+                }
+            }
+            return newValue;
+        }
+        int hash = hash(key);
+        int i = indexFor(hash, table.length);
+        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
+
+        if (table[i] instanceof Entry) {
+            int listSize = 0;
+            @SuppressWarnings("unchecked")
+            Entry<K,V> prev = (Entry<K,V>)table[i];
+            Entry<K,V> e = prev;
+
+            while (e != null) {
+                Entry<K,V> next = (Entry<K,V>)e.next;
+                if (e.hash == hash && Objects.equals(e.key, key)) {
+                    V oldValue = e.value;
+                    V newValue = remappingFunction.apply(key, oldValue);
+                    if (newValue != oldValue) {
+                        if (newValue == null) {
+                            modCount++;
+                            size--;
+                            if (prev == e)
+                                table[i] = next;
+                            else
+                                prev.next = next;
+                            e.recordRemoval(this);
+                        } else {
+                            e.value = newValue;
+                            e.recordAccess(this);
+                        }
+                    }
+                    return newValue;
+                }
+                prev = e;
+                e = next;
+                listSize++;
+            }
+            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
+        } else if (table[i] != null) {
+            TreeBin tb = (TreeBin)table[i];
+            TreeNode p = tb.getTreeNode(hash, key);
+            V oldValue = p == null ? null : (V)p.entry.value;
+            V newValue = remappingFunction.apply(key, oldValue);
+            if (newValue != oldValue) {
+                if (newValue == null) {
+                    Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                    modCount++;
+                    size--;
+                    tb.deleteTreeNode(p);
+                    pEntry.recordRemoval(this);
+                    if (tb.root == null || tb.first == null) {
+                        // assert tb.root == null && tb.first == null :
+                        //         "TreeBin.first and root should both be null";
+                        // TreeBin is now empty, we should blank this bin
+                        table[i] = null;
+                    }
+                } else {
+                    if (p != null) { // just update the value
+                        Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                        pEntry.value = newValue;
+                        pEntry.recordAccess(this);
+                    } else { // need to put new node
+                        p = tb.putTreeNode(hash, key, newValue, null);
+                        // assert p == null; // should have added a new node
+                        modCount++;
+                        size++;
+                        if (size >= threshold) {
+                            resize(2 * table.length);
+                        }
+                    }
+                }
+            }
+            return newValue;
         }
 
         V newValue = remappingFunction.apply(key, null);
         if (newValue != null) {
             modCount++;
-            addEntry(hash, key, newValue, i);
+            addEntry(hash, key, newValue, i, checkIfNeedTree);
         }
 
         return newValue;
@@ -830,40 +1770,96 @@
         if (table == EMPTY_TABLE) {
             inflateTable(threshold);
         }
-        int hash = (key == null) ? 0 : hash(key);
+        if (key == null) {
+            V oldValue = nullKeyEntry == null ? null : nullKeyEntry.value;
+            V newValue = oldValue == null ? value : remappingFunction.apply(oldValue, value);
+            if (newValue != null) {
+                putForNullKey(newValue);
+            } else if (nullKeyEntry != null) {
+                removeNullKey();
+            }
+            return newValue;
+        }
+        int hash = hash(key);
         int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-        Entry<K,V> prev = (Entry<K,V>)table[i];
-        Entry<K,V> e = prev;
+        boolean checkIfNeedTree = false; // Might we convert bin to a TreeBin?
 
-        while (e != null) {
-            Entry<K,V> next = e.next;
-            if (e.hash == hash && Objects.equals(e.key, key)) {
-                V oldValue = e.value;
-                V newValue = remappingFunction.apply(oldValue, value);
-                modCount++;
-                if (newValue == null) {
+        if (table[i] instanceof Entry) {
+            int listSize = 0;
+            @SuppressWarnings("unchecked")
+            Entry<K,V> prev = (Entry<K,V>)table[i];
+            Entry<K,V> e = prev;
+
+            while (e != null) {
+                Entry<K,V> next = (Entry<K,V>)e.next;
+                if (e.hash == hash && Objects.equals(e.key, key)) {
+                    V oldValue = e.value;
+                    V newValue = (oldValue == null) ? value :
+                                 remappingFunction.apply(oldValue, value);
+                    if (newValue == null) {
+                        modCount++;
+                        size--;
+                        if (prev == e)
+                            table[i] = next;
+                        else
+                            prev.next = next;
+                        e.recordRemoval(this);
+                    } else {
+                        e.value = newValue;
+                        e.recordAccess(this);
+                    }
+                    return newValue;
+                }
+                prev = e;
+                e = next;
+                listSize++;
+            }
+            // Didn't find, so fall through and (maybe) call addEntry() to add
+            // the Entry and check for TreeBin conversion.
+            checkIfNeedTree = listSize >= TreeBin.TREE_THRESHOLD;
+        } else if (table[i] != null) {
+            TreeBin tb = (TreeBin)table[i];
+            TreeNode p = tb.getTreeNode(hash, key);
+            V oldValue = p == null ? null : (V)p.entry.value;
+            V newValue = (oldValue == null) ? value :
+                         remappingFunction.apply(oldValue, value);
+            if (newValue == null) {
+                if (p != null) {
+                    Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                    modCount++;
                     size--;
-                    if (prev == e)
-                        table[i] = next;
-                    else
-                        prev.next = next;
-                    e.recordRemoval(this);
-                } else {
-                    e.value = newValue;
-                    e.recordAccess(this);
+                    tb.deleteTreeNode(p);
+                    pEntry.recordRemoval(this);
+
+                    if (tb.root == null || tb.first == null) {
+                        // assert tb.root == null && tb.first == null :
+                        //         "TreeBin.first and root should both be null";
+                        // TreeBin is now empty, we should blank this bin
+                        table[i] = null;
+                    }
                 }
-                return newValue;
+                return null;
+            } else if (newValue != oldValue) {
+                if (p != null) { // just update the value
+                    Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                    pEntry.value = newValue;
+                    pEntry.recordAccess(this);
+                } else { // need to put new node
+                    p = tb.putTreeNode(hash, key, newValue, null);
+                    // assert p == null; // should have added a new node
+                    modCount++;
+                    size++;
+                    if (size >= threshold) {
+                        resize(2 * table.length);
+                    }
+                }
             }
-            prev = e;
-            e = next;
+            return newValue;
         }
-
         if (value != null) {
             modCount++;
-            addEntry(hash, key, value, i);
+            addEntry(hash, key, value, i, checkIfNeedTree);
         }
-
         return value;
     }
 
@@ -873,36 +1869,65 @@
      * Removes and returns the entry associated with the specified key
      * in the HashMap.  Returns null if the HashMap contains no mapping
      * for this key.
+     *
+     * We don't bother converting TreeBins back to Entry lists if the bin falls
+     * back below TREE_THRESHOLD, but we do clear bins when removing the last
+     * TreeNode in a TreeBin.
      */
     final Entry<K,V> removeEntryForKey(Object key) {
         if (isEmpty()) {
             return null;
         }
-        int hash = (key == null) ? 0 : hash(key);
+        if (key == null) {
+            if (nullKeyEntry != null) {
+                return removeNullKey();
+            }
+            return null;
+        }
+        int hash = hash(key);
         int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
+
+        if (table[i] instanceof Entry) {
+            @SuppressWarnings("unchecked")
             Entry<K,V> prev = (Entry<K,V>)table[i];
-        Entry<K,V> e = prev;
+            Entry<K,V> e = prev;
 
-        while (e != null) {
-            Entry<K,V> next = e.next;
-            Object k;
-            if (e.hash == hash &&
-                ((k = e.key) == key || (key != null && key.equals(k)))) {
+            while (e != null) {
+                @SuppressWarnings("unchecked")
+                Entry<K,V> next = (Entry<K,V>) e.next;
+                if (e.hash == hash && Objects.equals(e.key, key)) {
+                    modCount++;
+                    size--;
+                    if (prev == e)
+                        table[i] = next;
+                    else
+                        prev.next = next;
+                    e.recordRemoval(this);
+                    return e;
+                }
+                prev = e;
+                e = next;
+            }
+        } else if (table[i] != null) {
+            TreeBin tb = ((TreeBin) table[i]);
+            TreeNode p = tb.getTreeNode(hash, (K)key);
+            if (p != null) {
+                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                // assert pEntry.key.equals(key);
                 modCount++;
                 size--;
-                if (prev == e)
-                    table[i] = next;
-                else
-                    prev.next = next;
-                e.recordRemoval(this);
-                return e;
+                tb.deleteTreeNode(p);
+                pEntry.recordRemoval(this);
+                if (tb.root == null || tb.first == null) {
+                    // assert tb.root == null && tb.first == null :
+                    //             "TreeBin.first and root should both be null";
+                    // TreeBin is now empty, we should blank this bin
+                    table[i] = null;
+                }
+                return pEntry;
             }
-            prev = e;
-            e = next;
         }
-
-        return e;
+        return null;
     }
 
     /**
@@ -915,29 +1940,75 @@
 
         Map.Entry<?,?> entry = (Map.Entry<?,?>) o;
         Object key = entry.getKey();
-        int hash = (key == null) ? 0 : hash(key);
+
+        if (key == null) {
+            if (entry.equals(nullKeyEntry)) {
+                return removeNullKey();
+            }
+            return null;
+        }
+
+        int hash = hash(key);
         int i = indexFor(hash, table.length);
-        @SuppressWarnings("unchecked")
-            Entry<K,V> prev = (Entry<K,V>)table[i];
-        Entry<K,V> e = prev;
 
-        while (e != null) {
-            Entry<K,V> next = e.next;
-            if (e.hash == hash && e.equals(entry)) {
+        if (table[i] instanceof Entry) {
+            @SuppressWarnings("unchecked")
+                Entry<K,V> prev = (Entry<K,V>)table[i];
+            Entry<K,V> e = prev;
+
+            while (e != null) {
+                @SuppressWarnings("unchecked")
+                Entry<K,V> next = (Entry<K,V>)e.next;
+                if (e.hash == hash && e.equals(entry)) {
+                    modCount++;
+                    size--;
+                    if (prev == e)
+                        table[i] = next;
+                    else
+                        prev.next = next;
+                    e.recordRemoval(this);
+                    return e;
+                }
+                prev = e;
+                e = next;
+            }
+        } else if (table[i] != null) {
+            TreeBin tb = ((TreeBin) table[i]);
+            TreeNode p = tb.getTreeNode(hash, (K)key);
+            if (p != null && p.entry.equals(entry)) {
+                @SuppressWarnings("unchecked")
+                Entry<K,V> pEntry = (Entry<K,V>)p.entry;
+                // assert pEntry.key.equals(key);
                 modCount++;
                 size--;
-                if (prev == e)
-                    table[i] = next;
-                else
-                    prev.next = next;
-                e.recordRemoval(this);
-                return e;
+                tb.deleteTreeNode(p);
+                pEntry.recordRemoval(this);
+                if (tb.root == null || tb.first == null) {
+                    // assert tb.root == null && tb.first == null :
+                    //             "TreeBin.first and root should both be null";
+                    // TreeBin is now empty, we should blank this bin
+                    table[i] = null;
+                }
+                return pEntry;
             }
-            prev = e;
-            e = next;
         }
+        return null;
+    }
 
-        return e;
+    /*
+     * Remove the mapping for the null key, and update internal accounting
+     * (size, modcount, recordRemoval, etc).
+     *
+     * Assumes nullKeyEntry is non-null.
+     */
+    private Entry<K,V> removeNullKey() {
+        // assert nullKeyEntry != null;
+        Entry<K,V> retVal = nullKeyEntry;
+        modCount++;
+        size--;
+        retVal.recordRemoval(this);
+        nullKeyEntry = null;
+        return retVal;
     }
 
     /**
@@ -946,6 +2017,9 @@
      */
     public void clear() {
         modCount++;
+        if (nullKeyEntry != null) {
+            nullKeyEntry = null;
+        }
         Arrays.fill(table, null);
         size = 0;
     }
@@ -959,27 +2033,58 @@
      *         specified value
      */
     public boolean containsValue(Object value) {
-        if (value == null)
+        if (value == null) {
             return containsNullValue();
-
-        Entry<?,?>[] tab = table;
-        for (int i = 0; i < tab.length; i++)
-            for (Entry<?,?> e = tab[i]; e != null; e = e.next)
-                if (value.equals(e.value))
-                    return true;
-        return false;
+        }
+        Object[] tab = table;
+        for (int i = 0; i < tab.length; i++) {
+            if (tab[i] instanceof Entry) {
+                Entry<?,?> e = (Entry<?,?>)tab[i];
+                for (; e != null; e = (Entry<?,?>)e.next) {
+                    if (value.equals(e.value)) {
+                        return true;
+                    }
+                }
+            } else if (tab[i] != null) {
+                TreeBin e = (TreeBin)tab[i];
+                TreeNode p = e.first;
+                for (; p != null; p = (TreeNode) p.entry.next) {
+                    if (value == p.entry.value || value.equals(p.entry.value)) {
+                        return true;
+                    }
+                }
+            }
+        }
+        // Didn't find value in table - could be in nullKeyEntry
+        return (nullKeyEntry != null && (value == nullKeyEntry.value ||
+                                         value.equals(nullKeyEntry.value)));
     }
 
     /**
      * Special-case code for containsValue with null argument
      */
     private boolean containsNullValue() {
-        Entry<?,?>[] tab = table;
-        for (int i = 0; i < tab.length; i++)
-            for (Entry<?,?> e = tab[i]; e != null; e = e.next)
-                if (e.value == null)
-                    return true;
-        return false;
+        Object[] tab = table;
+        for (int i = 0; i < tab.length; i++) {
+            if (tab[i] instanceof Entry) {
+                Entry<K,V> e = (Entry<K,V>)tab[i];
+                for (; e != null; e = (Entry<K,V>)e.next) {
+                    if (e.value == null) {
+                        return true;
+                    }
+                }
+            } else if (tab[i] != null) {
+                TreeBin e = (TreeBin)tab[i];
+                TreeNode p = e.first;
+                for (; p != null; p = (TreeNode) p.entry.next) {
+                    if (p.entry.value == null) {
+                        return true;
+                    }
+                }
+            }
+        }
+        // Didn't find value in table - could be in nullKeyEntry
+        return (nullKeyEntry != null && nullKeyEntry.value == null);
     }
 
     /**
@@ -1007,6 +2112,7 @@
         result.entrySet = null;
         result.modCount = 0;
         result.size = 0;
+        result.nullKeyEntry = null;
         result.init();
         result.putAllForCreate(this);
 
@@ -1016,13 +2122,13 @@
     static class Entry<K,V> implements Map.Entry<K,V> {
         final K key;
         V value;
-        Entry<K,V> next;
+        Object next; // an Entry, or a TreeNode
         final int hash;
 
         /**
          * Creates new entry.
          */
-        Entry(int h, K k, V v, Entry<K,V> n) {
+        Entry(int h, K k, V v, Object n) {
             value = v;
             next = n;
             key = k;
@@ -1054,7 +2160,7 @@
                 Object v2 = e.getValue();
                 if (v1 == v2 || (v1 != null && v1.equals(v2)))
                     return true;
-            }
+                }
             return false;
         }
 
@@ -1068,8 +2174,7 @@
 
         /**
          * This method is invoked whenever the value in an entry is
-         * overwritten by an invocation of put(k,v) for a key k that's already
-         * in the HashMap.
+         * overwritten for a key that's already in the HashMap.
          */
         void recordAccess(HashMap<K,V> m) {
         }
@@ -1082,50 +2187,96 @@
         }
     }
 
+    void addEntry(int hash, K key, V value, int bucketIndex) {
+        addEntry(hash, key, value, bucketIndex, true);
+    }
+
     /**
      * Adds a new entry with the specified key, value and hash code to
      * the specified bucket.  It is the responsibility of this
-     * method to resize the table if appropriate.
+     * method to resize the table if appropriate.  The new entry is then
+     * created by calling createEntry().
      *
      * Subclass overrides this to alter the behavior of put method.
+     *
+     * If checkIfNeedTree is false, it is known that this bucket will not need
+     * to be converted to a TreeBin, so don't bothering checking.
+     *
+     * Assumes key is not null.
      */
-    void addEntry(int hash, K key, V value, int bucketIndex) {
+    void addEntry(int hash, K key, V value, int bucketIndex, boolean checkIfNeedTree) {
+        // assert key != null;
         if ((size >= threshold) && (null != table[bucketIndex])) {
             resize(2 * table.length);
-            hash = (null != key) ? hash(key) : 0;
+            hash = hash(key);
             bucketIndex = indexFor(hash, table.length);
         }
-
-        createEntry(hash, key, value, bucketIndex);
+        createEntry(hash, key, value, bucketIndex, checkIfNeedTree);
     }
 
     /**
-     * Like addEntry except that this version is used when creating entries
+     * Called by addEntry(), and also used when creating entries
      * as part of Map construction or "pseudo-construction" (cloning,
-     * deserialization).  This version needn't worry about resizing the table.
+     * deserialization).  This version does not check for resizing of the table.
      *
-     * Subclass overrides this to alter the behavior of HashMap(Map),
-     * clone, and readObject.
+     * This method is responsible for converting a bucket to a TreeBin once
+     * TREE_THRESHOLD is reached. However if checkIfNeedTree is false, it is known
+     * that this bucket will not need to be converted to a TreeBin, so don't
+     * bother checking.  The new entry is constructed by calling newEntry().
+     *
+     * Assumes key is not null.
+     *
+     * Note: buckets already converted to a TreeBin don't call this method, but
+     * instead call TreeBin.putTreeNode() to create new entries.
      */
-    void createEntry(int hash, K key, V value, int bucketIndex) {
+    void createEntry(int hash, K key, V value, int bucketIndex, boolean checkIfNeedTree) {
+        // assert key != null;
         @SuppressWarnings("unchecked")
             Entry<K,V> e = (Entry<K,V>)table[bucketIndex];
-        table[bucketIndex] = new Entry<>(hash, key, value, e);
+        table[bucketIndex] = newEntry(hash, key, value, e);
         size++;
+
+        if (checkIfNeedTree) {
+            int listSize = 0;
+            for (e = (Entry<K,V>) table[bucketIndex]; e != null; e = (Entry<K,V>)e.next) {
+                listSize++;
+                if (listSize >= TreeBin.TREE_THRESHOLD) { // Convert to TreeBin
+                    if (comparableClassFor(key) != null) {
+                        TreeBin t = new TreeBin();
+                        t.populate((Entry)table[bucketIndex]);
+                        table[bucketIndex] = t;
+                    }
+                    break;
+                }
+            }
+        }
     }
 
+    /*
+     * Factory method to create a new Entry object.
+     */
+    Entry<K,V> newEntry(int hash, K key, V value, Object next) {
+        return new HashMap.Entry<>(hash, key, value, next);
+    }
+
+
     private abstract class HashIterator<E> implements Iterator<E> {
-        Entry<?,?> next;        // next entry to return
+        Object next;            // next entry to return, an Entry or a TreeNode
         int expectedModCount;   // For fast-fail
         int index;              // current slot
-        Entry<?,?> current;     // current entry
+        Object current;         // current entry, an Entry or a TreeNode
 
         HashIterator() {
             expectedModCount = modCount;
             if (size > 0) { // advance to first entry
-                Entry<?,?>[] t = table;
-                while (index < t.length && (next = t[index++]) == null)
-                    ;
+                if (nullKeyEntry != null) {
+                    // assert nullKeyEntry.next == null;
+                    // This works with nextEntry(): nullKeyEntry isa Entry, and
+                    // e.next will be null, so we'll hit the findNextBin() call.
+                    next = nullKeyEntry;
+                } else {
+                    findNextBin();
+                }
             }
         }
 
@@ -1135,19 +2286,28 @@
 
         @SuppressWarnings("unchecked")
         final Entry<K,V> nextEntry() {
-            if (modCount != expectedModCount)
+            if (modCount != expectedModCount) {
                 throw new ConcurrentModificationException();
-            Entry<?,?> e = next;
+            }
+            Object e = next;
+            Entry<K,V> retVal;
+
             if (e == null)
                 throw new NoSuchElementException();
 
-            if ((next = e.next) == null) {
-                Entry<?,?>[] t = table;
-                while (index < t.length && (next = t[index++]) == null)
-                    ;
+            if (e instanceof Entry) {
+                retVal = (Entry<K,V>)e;
+                next = ((Entry<K,V>)e).next;
+            } else { // TreeBin
+                retVal = (Entry<K,V>)((TreeNode)e).entry;
+                next = retVal.next;
+            }
+
+            if (next == null) { // Move to next bin
+                findNextBin();
             }
             current = e;
-            return (Entry<K,V>)e;
+            return retVal;
         }
 
         public void remove() {
@@ -1155,11 +2315,33 @@
                 throw new IllegalStateException();
             if (modCount != expectedModCount)
                 throw new ConcurrentModificationException();
-            Object k = current.key;
+            K k;
+
+            if (current instanceof Entry) {
+                k = ((Entry<K,V>)current).key;
+            } else {
+                k = ((Entry<K,V>)((TreeNode)current).entry).key;
+
+            }
             current = null;
             HashMap.this.removeEntryForKey(k);
             expectedModCount = modCount;
         }
+
+        /*
+         * Set 'next' to the first entry of the next non-empty bin in the table
+         */
+        private void findNextBin() {
+            // assert next == null;
+            Object[] t = table;
+
+            while (index < t.length && (next = t[index++]) == null)
+                ;
+            if (next instanceof HashMap.TreeBin) { // Point to the first TreeNode
+                next = ((TreeBin) next).first;
+                // assert next != null; // There should be no empty TreeBins
+            }
+        }
     }
 
     private final class ValueIterator extends HashIterator<V> {
@@ -1357,7 +2539,7 @@
         if (table==EMPTY_TABLE) {
             s.writeInt(roundUpToPowerOf2(threshold));
         } else {
-           s.writeInt(table.length);
+            s.writeInt(table.length);
         }
 
         // Write out size (number of Mappings)
@@ -1389,8 +2571,10 @@
         }
 
         // set other fields that need values
-        Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
-                sun.misc.Hashing.randomHashSeed(this));
+        if (Holder.USE_HASHSEED) {
+            Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
+                    sun.misc.Hashing.randomHashSeed(this));
+        }
         table = EMPTY_TABLE;
 
         // Read in number of buckets
@@ -1404,9 +2588,9 @@
 
         // capacity chosen by number of mappings and desired load (if >= 0.25)
         int capacity = (int) Math.min(
-                    mappings * Math.min(1 / loadFactor, 4.0f),
-                    // we have limits...
-                    HashMap.MAXIMUM_CAPACITY);
+                mappings * Math.min(1 / loadFactor, 4.0f),
+                // we have limits...
+                HashMap.MAXIMUM_CAPACITY);
 
         // allocate the bucket array;
         if (mappings > 0) {
@@ -1420,9 +2604,9 @@
         // Read the keys and values, and put the mappings in the HashMap
         for (int i=0; i<mappings; i++) {
             @SuppressWarnings("unchecked")
-                K key = (K) s.readObject();
+            K key = (K) s.readObject();
             @SuppressWarnings("unchecked")
-                V value = (V) s.readObject();
+            V value = (V) s.readObject();
             putForCreate(key, value);
         }
     }
@@ -1436,11 +2620,17 @@
      */
     static class HashMapSpliterator<K,V> {
         final HashMap<K,V> map;
-        HashMap.Entry<K,V> current; // current node
+        Object current;             // current node, can be Entry or TreeNode
         int index;                  // current index, modified on advance/split
         int fence;                  // one past last index
         int est;                    // size estimate
         int expectedModCount;       // for comodification checks
+        boolean acceptedNull;       // Have we accepted the null key?
+                                    // Without this, we can't distinguish
+                                    // between being at the very beginning (and
+                                    // needing to accept null), or being at the
+                                    // end of the list in bin 0.  In both cases,
+                                    // current == null && index == 0.
 
         HashMapSpliterator(HashMap<K,V> m, int origin,
                                int fence, int est,
@@ -1450,6 +2640,7 @@
             this.fence = fence;
             this.est = est;
             this.expectedModCount = expectedModCount;
+            this.acceptedNull = false;
         }
 
         final int getFence() { // initialize fence and size on first use
@@ -1479,9 +2670,15 @@
 
         public KeySpliterator<K,V> trySplit() {
             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
-            return (lo >= mid || current != null) ? null :
-                new KeySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
-                                        expectedModCount);
+            if (lo >= mid || current != null) {
+                return null;
+            } else {
+                KeySpliterator<K,V> retVal = new KeySpliterator<K,V>(map, lo,
+                                     index = mid, est >>>= 1, expectedModCount);
+                // Only 'this' Spliterator chould check for null.
+                retVal.acceptedNull = true;
+                return retVal;
+            }
         }
 
         @SuppressWarnings("unchecked")
@@ -1490,21 +2687,39 @@
             if (action == null)
                 throw new NullPointerException();
             HashMap<K,V> m = map;
-            HashMap.Entry<K,V>[] tab = (HashMap.Entry<K,V>[])m.table;
+            Object[] tab = m.table;
             if ((hi = fence) < 0) {
                 mc = expectedModCount = m.modCount;
                 hi = fence = tab.length;
             }
             else
                 mc = expectedModCount;
-            if (tab.length >= hi && (i = index) >= 0 && i < (index = hi)) {
-                HashMap.Entry<K,V> p = current;
+
+            if (!acceptedNull) {
+                acceptedNull = true;
+                if (m.nullKeyEntry != null) {
+                    action.accept(m.nullKeyEntry.key);
+                }
+            }
+            if (tab.length >= hi && (i = index) >= 0 &&
+                (i < (index = hi) || current != null)) {
+                Object p = current;
+                current = null;
                 do {
-                    if (p == null)
+                    if (p == null) {
                         p = tab[i++];
-                    else {
-                        action.accept(p.getKey());
-                        p = p.next;
+                        if (p instanceof HashMap.TreeBin) {
+                            p = ((HashMap.TreeBin)p).first;
+                        }
+                    } else {
+                        HashMap.Entry<K,V> entry;
+                        if (p instanceof HashMap.Entry) {
+                            entry = (HashMap.Entry<K,V>)p;
+                        } else {
+                            entry = (HashMap.Entry<K,V>)((TreeNode)p).entry;
+                        }
+                        action.accept(entry.key);
+                        p = entry.next;
                     }
                 } while (p != null || i < hi);
                 if (m.modCount != mc)
@@ -1517,14 +2732,34 @@
             int hi;
             if (action == null)
                 throw new NullPointerException();
-            HashMap.Entry<K,V>[] tab = (HashMap.Entry<K,V>[])map.table;
-            if (tab.length >= (hi = getFence()) && index >= 0) {
+            Object[] tab = map.table;
+            hi = getFence();
+
+            if (!acceptedNull) {
+                acceptedNull = true;
+                if (map.nullKeyEntry != null) {
+                    action.accept(map.nullKeyEntry.key);
+                    if (map.modCount != expectedModCount)
+                        throw new ConcurrentModificationException();
+                    return true;
+                }
+            }
+            if (tab.length >= hi && index >= 0) {
                 while (current != null || index < hi) {
-                    if (current == null)
+                    if (current == null) {
                         current = tab[index++];
-                    else {
-                        K k = current.getKey();
-                        current = current.next;
+                        if (current instanceof HashMap.TreeBin) {
+                            current = ((HashMap.TreeBin)current).first;
+                        }
+                    } else {
+                        HashMap.Entry<K,V> entry;
+                        if (current instanceof HashMap.Entry) {
+                            entry = (HashMap.Entry<K,V>)current;
+                        } else {
+                            entry = (HashMap.Entry<K,V>)((TreeNode)current).entry;
+                        }
+                        K k = entry.key;
+                        current = entry.next;
                         action.accept(k);
                         if (map.modCount != expectedModCount)
                             throw new ConcurrentModificationException();
@@ -1551,9 +2786,15 @@
 
         public ValueSpliterator<K,V> trySplit() {
             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
-            return (lo >= mid || current != null) ? null :
-                new ValueSpliterator<K,V>(map, lo, index = mid, est >>>= 1,
-                                          expectedModCount);
+            if (lo >= mid || current != null) {
+                return null;
+            } else {
+                ValueSpliterator<K,V> retVal = new ValueSpliterator<K,V>(map,
+                                 lo, index = mid, est >>>= 1, expectedModCount);
+                // Only 'this' Spliterator chould check for null.
+                retVal.acceptedNull = true;
+                return retVal;
+            }
         }
 
         @SuppressWarnings("unchecked")
@@ -1562,21 +2803,39 @@
             if (action == null)
                 throw new NullPointerException();
             HashMap<K,V> m = map;
-            HashMap.Entry<K,V>[] tab = (HashMap.Entry<K,V>[])m.table;
+            Object[] tab = m.table;
             if ((hi = fence) < 0) {
                 mc = expectedModCount = m.modCount;
                 hi = fence = tab.length;
             }
             else
                 mc = expectedModCount;
-            if (tab.length >= hi && (i = index) >= 0 && i < (index = hi)) {
-                HashMap.Entry<K,V> p = current;
+
+            if (!acceptedNull) {
+                acceptedNull = true;
+                if (m.nullKeyEntry != null) {
+                    action.accept(m.nullKeyEntry.value);
+                }
+            }
+            if (tab.length >= hi && (i = index) >= 0 &&
+                (i < (index = hi) || current != null)) {
+                Object p = current;
+                current = null;
                 do {
-                    if (p == null)
+                    if (p == null) {
                         p = tab[i++];
-                    else {
-                        action.accept(p.getValue());
-                        p = p.next;
+                        if (p instanceof HashMap.TreeBin) {
+                            p = ((HashMap.TreeBin)p).first;
+                        }
+                    } else {
+                        HashMap.Entry<K,V> entry;
+                        if (p instanceof HashMap.Entry) {
+                            entry = (HashMap.Entry<K,V>)p;
+                        } else {
+                            entry = (HashMap.Entry<K,V>)((TreeNode)p).entry;
+                        }
+                        action.accept(entry.value);
+                        p = entry.next;
                     }
                 } while (p != null || i < hi);
                 if (m.modCount != mc)
@@ -1589,14 +2848,34 @@
             int hi;
             if (action == null)
                 throw new NullPointerException();
-            HashMap.Entry<K,V>[] tab = (HashMap.Entry<K,V>[])map.table;
-            if (tab.length >= (hi = getFence()) && index >= 0) {
+            Object[] tab = map.table;
+            hi = getFence();
+
+            if (!acceptedNull) {
+                acceptedNull = true;
+                if (map.nullKeyEntry != null) {
+                    action.accept(map.nullKeyEntry.value);
+                    if (map.modCount != expectedModCount)
+                        throw new ConcurrentModificationException();
+                    return true;
+                }
+            }
+            if (tab.length >= hi && index >= 0) {
                 while (current != null || index < hi) {
-                    if (current == null)
+                    if (current == null) {
                         current = tab[index++];
-                    else {
-                        V v = current.getValue();
-                        current = current.next;
+                        if (current instanceof HashMap.TreeBin) {
+                            current = ((HashMap.TreeBin)current).first;
+                        }
+                    } else {
+                        HashMap.Entry<K,V> entry;
+                        if (current instanceof HashMap.Entry) {
+                            entry = (Entry<K,V>)current;
+                        } else {
+                            entry = (Entry<K,V>)((TreeNode)current).entry;
+                        }
+                        V v = entry.value;
+                        current = entry.next;
                         action.accept(v);
                         if (map.modCount != expectedModCount)
                             throw new ConcurrentModificationException();
@@ -1622,9 +2901,15 @@
 
         public EntrySpliterator<K,V> trySplit() {
             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
-            return (lo >= mid || current != null) ? null :
-                new EntrySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
-                                          expectedModCount);
+            if (lo >= mid || current != null) {
+                return null;
+            } else {
+                EntrySpliterator<K,V> retVal = new EntrySpliterator<K,V>(map,
+                                 lo, index = mid, est >>>= 1, expectedModCount);
+                // Only 'this' Spliterator chould check for null.
+                retVal.acceptedNull = true;
+                return retVal;
+            }
         }
 
         @SuppressWarnings("unchecked")
@@ -1633,21 +2918,40 @@
             if (action == null)
                 throw new NullPointerException();
             HashMap<K,V> m = map;
-            HashMap.Entry<K,V>[] tab = (HashMap.Entry<K,V>[])m.table;
+            Object[] tab = m.table;
             if ((hi = fence) < 0) {
                 mc = expectedModCount = m.modCount;
                 hi = fence = tab.length;
             }
             else
                 mc = expectedModCount;
-            if (tab.length >= hi && (i = index) >= 0 && i < (index = hi)) {
-                HashMap.Entry<K,V> p = current;
+
+            if (!acceptedNull) {
+                acceptedNull = true;
+                if (m.nullKeyEntry != null) {
+                    action.accept(m.nullKeyEntry);
+                }
+            }
+            if (tab.length >= hi && (i = index) >= 0 &&
+                (i < (index = hi) || current != null)) {
+                Object p = current;
+                current = null;
                 do {
-                    if (p == null)
+                    if (p == null) {
                         p = tab[i++];
-                    else {
-                        action.accept(p);
-                        p = p.next;
+                        if (p instanceof HashMap.TreeBin) {
+                            p = ((HashMap.TreeBin)p).first;
+                        }
+                    } else {
+                        HashMap.Entry<K,V> entry;
+                        if (p instanceof HashMap.Entry) {
+                            entry = (HashMap.Entry<K,V>)p;
+                        } else {
+                            entry = (HashMap.Entry<K,V>)((TreeNode)p).entry;
+                        }
+                        action.accept(entry);
+                        p = entry.next;
+
                     }
                 } while (p != null || i < hi);
                 if (m.modCount != mc)
@@ -1660,14 +2964,33 @@
             int hi;
             if (action == null)
                 throw new NullPointerException();
-            HashMap.Entry<K,V>[] tab = (HashMap.Entry<K,V>[])map.table;
-            if (tab.length >= (hi = getFence()) && index >= 0) {
+            Object[] tab = map.table;
+            hi = getFence();
+
+            if (!acceptedNull) {
+                acceptedNull = true;
+                if (map.nullKeyEntry != null) {
+                    action.accept(map.nullKeyEntry);
+                    if (map.modCount != expectedModCount)
+                        throw new ConcurrentModificationException();
+                    return true;
+                }
+            }
+            if (tab.length >= hi && index >= 0) {
                 while (current != null || index < hi) {
-                    if (current == null)
+                    if (current == null) {
                         current = tab[index++];
-                    else {
-                        HashMap.Entry<K,V> e = current;
-                        current = current.next;
+                        if (current instanceof HashMap.TreeBin) {
+                            current = ((HashMap.TreeBin)current).first;
+                        }
+                    } else {
+                        HashMap.Entry<K,V> e;
+                        if (current instanceof HashMap.Entry) {
+                            e = (Entry<K,V>)current;
+                        } else {
+                            e = (Entry<K,V>)((TreeNode)current).entry;
+                        }
+                        current = e.next;
                         action.accept(e);
                         if (map.modCount != expectedModCount)
                             throw new ConcurrentModificationException();
--- a/src/share/classes/java/util/Hashtable.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/Hashtable.java	Wed Jun 05 12:31:59 2013 -0700
@@ -180,13 +180,27 @@
          */
         static final long HASHSEED_OFFSET;
 
+        static final boolean USE_HASHSEED;
+
         static {
-            try {
-                UNSAFE = sun.misc.Unsafe.getUnsafe();
-                HASHSEED_OFFSET = UNSAFE.objectFieldOffset(
-                    Hashtable.class.getDeclaredField("hashSeed"));
-            } catch (NoSuchFieldException | SecurityException e) {
-                throw new InternalError("Failed to record hashSeed offset", e);
+            String hashSeedProp = java.security.AccessController.doPrivileged(
+                    new sun.security.action.GetPropertyAction(
+                        "jdk.map.useRandomSeed"));
+            boolean localBool = (null != hashSeedProp)
+                    ? Boolean.parseBoolean(hashSeedProp) : false;
+            USE_HASHSEED = localBool;
+
+            if (USE_HASHSEED) {
+                try {
+                    UNSAFE = sun.misc.Unsafe.getUnsafe();
+                    HASHSEED_OFFSET = UNSAFE.objectFieldOffset(
+                        Hashtable.class.getDeclaredField("hashSeed"));
+                } catch (NoSuchFieldException | SecurityException e) {
+                    throw new InternalError("Failed to record hashSeed offset", e);
+                }
+            } else {
+                UNSAFE = null;
+                HASHSEED_OFFSET = 0;
             }
         }
     }
@@ -194,21 +208,24 @@
     /**
      * A randomizing value associated with this instance that is applied to
      * hash code of keys to make hash collisions harder to find.
+     *
+     * Non-final so it can be set lazily, but be sure not to set more than once.
      */
-    transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this);
+    transient final int hashSeed;
+
+    /**
+     * Return an initial value for the hashSeed, or 0 if the random seed is not
+     * enabled.
+     */
+    final int initHashSeed() {
+        if (sun.misc.VM.isBooted() && Holder.USE_HASHSEED) {
+            return sun.misc.Hashing.randomHashSeed(this);
+        }
+        return 0;
+    }
 
     private int hash(Object k) {
-        if (k instanceof String) {
-            return ((String)k).hash32();
-        }
-
-        int h = hashSeed ^ k.hashCode();
-
-        // This function ensures that hashCodes that differ only by
-        // constant multiples at each bit position have a bounded
-        // number of collisions (approximately 8 at default load factor).
-        h ^= (h >>> 20) ^ (h >>> 12);
-        return h ^ (h >>> 7) ^ (h >>> 4);
+        return hashSeed ^ k.hashCode();
     }
 
     /**
@@ -232,6 +249,7 @@
         this.loadFactor = loadFactor;
         table = new Entry<?,?>[initialCapacity];
         threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
+        hashSeed = initHashSeed();
     }
 
     /**
@@ -1187,8 +1205,10 @@
         s.defaultReadObject();
 
         // set hashMask
-        Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
-                sun.misc.Hashing.randomHashSeed(this));
+        if (Holder.USE_HASHSEED) {
+            Holder.UNSAFE.putIntVolatile(this, Holder.HASHSEED_OFFSET,
+                    sun.misc.Hashing.randomHashSeed(this));
+        }
 
         // Read the original length of the array and number of elements
         int origlength = s.readInt();
--- a/src/share/classes/java/util/IntSummaryStatistics.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/IntSummaryStatistics.java	Wed Jun 05 12:31:59 2013 -0700
@@ -159,7 +159,7 @@
      */
     public String toString() {
         return String.format(
-            "%s{count=%d, sum=%d, min=%d, average=%d, max=%d}",
+            "%s{count=%d, sum=%d, min=%d, average=%f, max=%d}",
             this.getClass().getSimpleName(),
             getCount(),
             getSum(),
--- a/src/share/classes/java/util/LinkedHashMap.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/LinkedHashMap.java	Wed Jun 05 12:31:59 2013 -0700
@@ -55,9 +55,9 @@
  * order they were presented.)
  *
  * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is
- * provided to create a linked hash map whose order of iteration is the order
- * in which its entries were last accessed, from least-recently accessed to
- * most-recently (<i>access-order</i>).  This kind of map is well-suited to
+ * provided to create a <tt>LinkedHashMap</tt> whose order of iteration is the
+ * order in which its entries were last accessed, from least-recently accessed
+ * to most-recently (<i>access-order</i>).  This kind of map is well-suited to
  * building LRU caches.  Invoking the <tt>put</tt> or <tt>get</tt> method
  * results in an access to the corresponding entry (assuming it exists after
  * the invocation completes).  The <tt>putAll</tt> method generates one entry
@@ -243,23 +243,6 @@
     }
 
     /**
-     * Transfers all entries to new table array.  This method is called
-     * by superclass resize.  It is overridden for performance, as it is
-     * faster to iterate using our linked list.
-     */
-    @Override
-    @SuppressWarnings("unchecked")
-    void transfer(HashMap.Entry[] newTable) {
-        int newCapacity = newTable.length;
-        for (Entry<K,V> e = header.after; e != header; e = e.after) {
-            int index = indexFor(e.hash, newCapacity);
-            e.next = (HashMap.Entry<K,V>)newTable[index];
-            newTable[index] = e;
-        }
-    }
-
-
-    /**
      * Returns <tt>true</tt> if this map maps one or more keys to the
      * specified value.
      *
@@ -320,7 +303,7 @@
         // These fields comprise the doubly linked list used for iteration.
         Entry<K,V> before, after;
 
-        Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
+        Entry(int hash, K key, V value, Object next) {
             super(hash, key, value, next);
         }
 
@@ -344,7 +327,7 @@
 
         /**
          * This method is invoked by the superclass whenever the value
-         * of a pre-existing entry is read by Map.get or modified by Map.set.
+         * of a pre-existing entry is read by Map.get or modified by Map.put.
          * If the enclosing Map is access-ordered, it moves the entry
          * to the end of the list; otherwise, it does nothing.
          */
@@ -422,8 +405,9 @@
      * allocated entry to get inserted at the end of the linked list and
      * removes the eldest entry if appropriate.
      */
-    void addEntry(int hash, K key, V value, int bucketIndex) {
-        super.addEntry(hash, key, value, bucketIndex);
+    @Override
+    void addEntry(int hash, K key, V value, int bucketIndex, boolean checkIfNeedTree) {
+        super.addEntry(hash, key, value, bucketIndex, checkIfNeedTree);
 
         // Remove eldest entry if instructed
         Entry<K,V> eldest = header.after;
@@ -432,17 +416,14 @@
         }
     }
 
-    /**
-     * This override differs from addEntry in that it doesn't resize the
-     * table or remove the eldest entry.
+    /*
+     * Create a new LinkedHashMap.Entry and setup the before/after pointers
      */
-    void createEntry(int hash, K key, V value, int bucketIndex) {
-        @SuppressWarnings("unchecked")
-            HashMap.Entry<K,V> old = (HashMap.Entry<K,V>)table[bucketIndex];
-        Entry<K,V> e = new Entry<>(hash, key, value, old);
-        table[bucketIndex] = e;
-        e.addBefore(header);
-        size++;
+    @Override
+    HashMap.Entry<K,V> newEntry(int hash, K key, V value, Object next) {
+        Entry<K,V> newEntry = new Entry<>(hash, key, value, next);
+        newEntry.addBefore(header);
+        return newEntry;
     }
 
     /**
--- a/src/share/classes/java/util/LongSummaryStatistics.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/LongSummaryStatistics.java	Wed Jun 05 12:31:59 2013 -0700
@@ -171,7 +171,7 @@
      */
     public String toString() {
         return String.format(
-            "%s{count=%d, sum=%d, min=%d, average=%d, max=%d}",
+            "%s{count=%d, sum=%d, min=%d, average=%f, max=%d}",
             this.getClass().getSimpleName(),
             getCount(),
             getSum(),
--- a/src/share/classes/java/util/PrimitiveIterator.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/PrimitiveIterator.java	Wed Jun 05 12:31:59 2013 -0700
@@ -91,6 +91,7 @@
          * @throws NullPointerException if the specified action is null
          */
         default void forEachRemaining(IntConsumer action) {
+            Objects.requireNonNull(action);
             while (hasNext())
                 action.accept(nextInt());
         }
@@ -123,6 +124,8 @@
                 forEachRemaining((IntConsumer) action);
             }
             else {
+                // The method reference action::accept is never null
+                Objects.requireNonNull(action);
                 if (Tripwire.ENABLED)
                     Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfInt.forEachRemainingInt(action::accept)");
                 forEachRemaining((IntConsumer) action::accept);
@@ -162,6 +165,7 @@
          * @throws NullPointerException if the specified action is null
          */
         default void forEachRemaining(LongConsumer action) {
+            Objects.requireNonNull(action);
             while (hasNext())
                 action.accept(nextLong());
         }
@@ -194,6 +198,8 @@
                 forEachRemaining((LongConsumer) action);
             }
             else {
+                // The method reference action::accept is never null
+                Objects.requireNonNull(action);
                 if (Tripwire.ENABLED)
                     Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfLong.forEachRemainingLong(action::accept)");
                 forEachRemaining((LongConsumer) action::accept);
@@ -232,6 +238,7 @@
          * @throws NullPointerException if the specified action is null
          */
         default void forEachRemaining(DoubleConsumer action) {
+            Objects.requireNonNull(action);
             while (hasNext())
                 action.accept(nextDouble());
         }
@@ -265,6 +272,8 @@
                 forEachRemaining((DoubleConsumer) action);
             }
             else {
+                // The method reference action::accept is never null
+                Objects.requireNonNull(action);
                 if (Tripwire.ENABLED)
                     Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfDouble.forEachRemainingDouble(action::accept)");
                 forEachRemaining((DoubleConsumer) action::accept);
--- a/src/share/classes/java/util/Spliterator.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/Spliterator.java	Wed Jun 05 12:31:59 2013 -0700
@@ -394,9 +394,9 @@
      * Convenience method that returns {@link #estimateSize()} if this
      * Spliterator is {@link #SIZED}, else {@code -1}.
      * @implSpec
-     * The default returns the result of {@code estimateSize()} if the
-     * Spliterator reports a characteristic of {@code SIZED}, and {@code -1}
-     * otherwise.
+     * The default implementation returns the result of {@code estimateSize()}
+     * if the Spliterator reports a characteristic of {@code SIZED}, and
+     * {@code -1} otherwise.
      *
      * @return the exact size, if known, else {@code -1}.
      */
--- a/src/share/classes/java/util/StringJoiner.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/StringJoiner.java	Wed Jun 05 12:31:59 2013 -0700
@@ -29,14 +29,6 @@
  * by a delimiter and optionally starting with a supplied prefix
  * and ending with a supplied suffix.
  * <p>
- * For example, the String {@code "[George:Sally:Fred]"} may
- * be constructed as follows:
- * <pre> {@code
- *     StringJoiner sj = new StringJoiner(":", "[", "]");
- *     sj.add("George").add("Sally").add("Fred");
- *     String desiredString = sj.toString();
- * }</pre>
- * <p>
  * Prior to adding something to the {@code StringJoiner}, its
  * {@code sj.toString()} method will, by default, return {@code prefix + suffix}.
  * However, if the {@code setEmptyValue} method is called, the {@code emptyValue}
@@ -45,17 +37,28 @@
  * <code>"{}"</code>, where the {@code prefix} is <code>"{"</code>, the
  * {@code suffix} is <code>"}"</code> and nothing has been added to the
  * {@code StringJoiner}.
+ *
+ * @apiNote
+ * <p>The String {@code "[George:Sally:Fred]"} may be constructed as follows:
+ *
+ * <pre> {@code
+ * StringJoiner sj = new StringJoiner(":", "[", "]");
+ * sj.add("George").add("Sally").add("Fred");
+ * String desiredString = sj.toString();
+ * }</pre>
  * <p>
  * A {@code StringJoiner} may be employed to create formatted output from a
- * collection using lambda expressions as shown in the following example.
+ * {@link java.util.stream.Stream} using
+ * {@link java.util.stream.Collectors#toStringJoiner}. For example:
  *
  * <pre> {@code
- *     List<Person> people = ...
- *     String commaSeparatedNames =
- *         people.map(p -> p.getName()).into(new StringJoiner(", ")).toString();
+ * List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
+ * String commaSeparatedNumbers = numbers.stream()
+ *     .map(i -> i.toString())
+ *     .collect(Collectors.toStringJoiner(", ")).toString();
  * }</pre>
  *
- * @author Jim Gish
+ * @see java.util.stream.Collectors#toStringJoiner
  * @since  1.8
 */
 public final class StringJoiner {
--- a/src/share/classes/java/util/WeakHashMap.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/WeakHashMap.java	Wed Jun 05 12:31:59 2013 -0700
@@ -187,11 +187,37 @@
      */
     int modCount;
 
+    private static class Holder {
+        static final boolean USE_HASHSEED;
+
+        static {
+            String hashSeedProp = java.security.AccessController.doPrivileged(
+                    new sun.security.action.GetPropertyAction(
+                        "jdk.map.useRandomSeed"));
+            boolean localBool = (null != hashSeedProp)
+                    ? Boolean.parseBoolean(hashSeedProp) : false;
+            USE_HASHSEED = localBool;
+        }
+    }
+
     /**
      * A randomizing value associated with this instance that is applied to
      * hash code of keys to make hash collisions harder to find.
+     *
+     * Non-final so it can be set lazily, but be sure not to set more than once.
      */
-    transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this);
+    transient int hashSeed;
+
+    /**
+     * Initialize the hashing mask value.
+     */
+    final void initHashSeed() {
+        if (sun.misc.VM.isBooted() && Holder.USE_HASHSEED) {
+            // Do not set hashSeed more than once!
+            // assert hashSeed == 0;
+            hashSeed = sun.misc.Hashing.randomHashSeed(this);
+        }
+    }
 
     @SuppressWarnings("unchecked")
     private Entry<K,V>[] newTable(int n) {
@@ -223,6 +249,7 @@
         table = newTable(capacity);
         this.loadFactor = loadFactor;
         threshold = (int)(capacity * loadFactor);
+        initHashSeed();
     }
 
     /**
@@ -298,10 +325,7 @@
      * in lower bits.
      */
     final int hash(Object k) {
-        if (k instanceof String) {
-            return ((String) k).hash32();
-        }
-        int  h = hashSeed ^ k.hashCode();
+        int h = hashSeed ^ k.hashCode();
 
         // This function ensures that hashCodes that differ only by
         // constant multiples at each bit position have a bounded
@@ -1076,9 +1100,10 @@
             }
             else
                 mc = expectedModCount;
-            if (tab.length >= hi && (i = index) >= 0 && i < hi) {
-                index = hi;
+            if (tab.length >= hi && (i = index) >= 0 &&
+                (i < (index = hi) || current != null)) {
                 WeakHashMap.Entry<K,V> p = current;
+                current = null; // exhaust
                 do {
                     if (p == null)
                         p = tab[i++];
@@ -1155,9 +1180,10 @@
             }
             else
                 mc = expectedModCount;
-            if (tab.length >= hi && (i = index) >= 0 && i < hi) {
-                index = hi;
+            if (tab.length >= hi && (i = index) >= 0 &&
+                (i < (index = hi) || current != null)) {
                 WeakHashMap.Entry<K,V> p = current;
+                current = null; // exhaust
                 do {
                     if (p == null)
                         p = tab[i++];
@@ -1232,9 +1258,10 @@
             }
             else
                 mc = expectedModCount;
-            if (tab.length >= hi && (i = index) >= 0 && i < hi) {
-                index = hi;
+            if (tab.length >= hi && (i = index) >= 0 &&
+                (i < (index = hi) || current != null)) {
                 WeakHashMap.Entry<K,V> p = current;
+                current = null; // exhaust
                 do {
                     if (p == null)
                         p = tab[i++];
--- a/src/share/classes/java/util/concurrent/ConcurrentHashMap.java	Wed Jun 05 12:30:02 2013 -0700
+++ b/src/share/classes/java/util/concurrent/ConcurrentHashMap.java	Wed Jun 05 12:31:59 2013 -0700
@@ -34,14 +34,47 @@
  */
 
 package java.util.concurrent;
-import java.io.ObjectInputStream;
-import java.util.concurrent.locks.*;
-import java.util.*;
 import java.io.Serializable;
+import java.io.ObjectStreamField;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.AbstractMap;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.ConcurrentModificationException;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.Spliterator;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.concurrent.locks.StampedLock;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
+import java.util.function.BinaryOperator;
+import java.util.function.Consumer;
+import java.util.function.DoubleBinaryOperator;
+import java.util.function.Function;
+import java.util.function.IntBinaryOperator;
+import java.util.function.LongBinaryOperator;
+import java.util.function.ToDoubleBiFunction;
+import java.util.function.ToDoubleFunction;
+import java.util.function.ToIntBiFunction;
+import java.util.function.ToIntFunction;
+import java.util.function.ToLongBiFunction;
+import java.util.function.ToLongFunction;
+import java.util.stream.Stream;
 
 /**
  * A hash table supporting full concurrency of retrievals and
- * adjustable expected concurrency for updates. This class obeys the
+ * high expected concurrency for updates. This class obeys the
  * same functional specification as {@link java.util.Hashtable}, and
  * includes versions of methods corresponding to each method of
  * {@code Hashtable}. However, even though all operations are
@@ -51,35 +84,61 @@
  * interoperable with {@code Hashtable} in programs that rely on its
  * thread safety but not on its synchronization details.
  *
- * <p> Retrieval operations (including {@code get}) generally do not
- * block, so may overlap with update operations (including
- * {@code put} and {@code remove}). Retrievals reflect the results
- * of the most recently <em>completed</em> update operations holding
- * upon their onset.  For aggregate operations such as {@code putAll}
- * and {@code clear}, concurrent retrievals may reflect insertion or
- * removal of only some entries.  Similarly, Iterators and
- * Enumerations return elements reflecting the state of the hash table
- * at some point at or since the creation of the iterator/enumeration.
- * They do <em>not</em> throw {@link ConcurrentModificationException}.
- * However, iterators are designed to be used by only one thread at a time.
+ * <p>Retrieval operations (including {@code get}) generally do not
+ * block, so may overlap with update operations (including {@code put}
+ * and {@code remove}). Retrievals reflect the results of the most
+ * recently <em>completed</em> update operations holding upon their
+ * onset. (More formally, an update operation for a given key bears a
+ * <em>happens-before</em> relation with any (non-null) retrieval for
+ * that key reporting the updated value.)  For aggregate operations
+ * such as {@code putAll} and {@code clear}, concurrent retrievals may
+ * reflect insertion or removal of only some entries.  Similarly,
+ * Iterators and Enumerations return elements reflecting the state of
+ * the hash table at some point at or since the creation of the
+ * iterator/enumeration.  They do <em>not</em> throw {@link
+ * ConcurrentModificationException}.  However, iterators are designed
+ * to be used by only one thread at a time.  Bear in mind that the
+ * results of aggregate status methods including {@code size}, {@code
+ * isEmpty}, and {@code containsValue} are typically useful only when
+ * a map is not undergoing concurrent updates in other threads.
+ * Otherwise the results of these methods reflect transient states
+ * that may be adequate for monitoring or estimation purposes, but not
+ * for program control.
  *
- * <p> The allowed concurrency among update operations is guided by
- * the optional {@code concurrencyLevel} constructor argument
- * (default {@code 16}), which is used as a hint for internal sizing.  The
- * table is internally partitioned to try to permit the indicated
- * number of concurrent updates without contention. Because placement
- * in hash tables is essentially random, the actual concurrency will
- * vary.  Ideally, you should choose a value to accommodate as many
- * threads as will ever concurrently modify the table. Using a
- * significantly higher value than you need can waste space and time,
- * and a significantly lower value can lead to thread contention. But
- * overestimates and underestimates within an order of magnitude do
- * not usually have much noticeable impact. A value of one is
- * appropriate when it is known that only one thread will modify and
- * all others will only read. Also, resizing this or any other kind of
- * hash table is a relatively slow operation, so, when possible, it is
- * a good idea to provide estimates of expected table sizes in
- * constructors.
+ * <p>The table is dynamically expanded when there are too many
+ * collisions (i.e., keys that have distinct hash codes but fall into
+ * the same slot modulo the table size), with the expected average
+ * effect of maintaining roughly two bins per mapping (corresponding
+ * to a 0.75 load factor threshold for resizing). There may be much
+ * variance around this average as mappings are added and removed, but
+ * overall, this maintains a commonly accepted time/space tradeoff for
+ * hash tables.  However, resizing this or any other kind of hash
+ * table may be a relatively slow operation. When possible, it is a
+ * good idea to provide a size estimate as an optional {@code
+ * initialCapacity} constructor argument. An additional optional
+ * {@code loadFactor} constructor argument provides a further means of
+ * customizing initial table capacity by specifying the table density
+ * to be used in calculating the amount of space to allocate for the
+ * given number of elements.  Also, for compatibility with previous
+ * versions of this class, constructors may optionally specify an
+ * expected {@code concurrencyLevel} as an additional hint for
+ * internal sizing.  Note that using many keys with exactly the same
+ * {@code hashCode()} is a sure way to slow down performance of any
+ * hash table. To ameliorate impact, when keys are {@link Comparable},
+ * this class may use comparison order among keys to help break ties.
+ *
+ * <p>A {@link Set} projection of a ConcurrentHashMap may be created
+ * (using {@link #newKeySet()} or {@link #newKeySet(int)}), or viewed
+ * (using {@link #keySet(Object)} when only keys are of interest, and the
+ * mapped values are (perhaps transiently) not used or all take the
+ * same mapping value.
+ *
+ * <p>A ConcurrentHashMap can be used as scalable frequency map (a
+ * form of histogram or multiset) by using {@link
+ * java.util.concurrent.atomic.LongAdder} values and initializing via
+ * {@link #computeIfAbsent computeIfAbsent}. For example, to add a count
+ * to a {@code ConcurrentHashMap<String,LongAdder> freqs}, you can use
+ * {@code freqs.computeIfAbsent(k -> new LongAdder()).increment();}
  *
  * <p>This class and its views and iterators implement all of the
  * <em>optional</em> methods of the {@link Map} and {@link Iterator}
@@ -88,6 +147,114 @@
  * <p>Like {@link Hashtable} but unlike {@link HashMap}, this class
  * does <em>not</em> allow {@code null} to be used as a key or value.
  *
+ * <p>ConcurrentHashMaps support a set of sequential and parallel bulk
+ * operations that, unlike most {@link Stream} methods, are designed
+ * to be safely, and often sensibly, applied even with maps that are
+ * being concurrently updated by other threads; for example, when
+ * computing a snapshot summary of the values in a shared registry.
+ * There are three kinds of operation, each with four forms, accepting
+ * functions with Keys, Values, Entries, and (Key, Value) arguments
+ * and/or return values. Because the elements of a ConcurrentHashMap
+ * are not ordered in any particular way, and may be processed in
+ * different orders in different parallel executions, the correctness
+ * of supplied functions should not depend on any ordering, or on any
+ * other objects or values that may transiently change while
+ * computation is in progress; and except for forEach actions, should
+ * ideally be side-effect-free. Bulk operations on {@link java.util.Map.Entry}
+ * objects do not support method {@code setValue}.
+ *
+ * <ul>
+ * <li> forEach: Perform a given action on each element.
+ * A variant form applies a given transformation on each element
+ * before performing the action.</li>
+ *
+ * <li> search: Return the first available non-null result of
+ * applying a given function on each element; skipping further
+ * search when a result is found.</li>
+ *
+ * <li> reduce: Accumulate each element.  The supplied reduction
+ * function cannot rely on ordering (more formally, it should be
+ * both associative and commutative).  There are five variants:
+ *
+ * <ul>
+ *
+ * <li> Plain reductions. (There is not a form of this method for
+ * (key, value) function arguments since there is no corresponding
+ * return type.)</li>
+ *
+ * <li> Mapped reductions that accumulate the results of a given
+ * function applied to each element.</li>
+ *
+ * <li> Reductions to scalar doubles, longs, and ints, using a
+ * given basis value.</li>
+ *
+ * </ul>
+ * </li>
+ * </ul>
+ *
+ * <p>These bulk operations accept a {@code parallelismThreshold}
+ * argument. Methods proceed sequentially if the current map size is
+ * estimated to be less than the given threshold. Using a value of
+ * {@code Long.MAX_VALUE} suppresses all parallelism.  Using a value
+ * of {@code 1} results in maximal parallelism by partitioning into
+ * enough subtasks to fully utilize the {@link
+ * ForkJoinPool#commonPool()} that is used for all parallel
+ * computations. Normally, you would initially choose one of these
+ * extreme values, and then measure performance of using in-between
+ * values that trade off overhead versus throughput.
+ *
+ * <p>The concurrency properties of bulk operations follow
+ * from those of ConcurrentHashMap: Any non-null result returned
+ * from {@code get(key)} and related access methods bears a
+ * happens-before relation with the associated insertion or
+ * update.  The result of any bulk operation reflects the
+ * composition of these per-element relations (but is not
+ * necessarily atomic with respect to the map as a whole unless it
+ * is somehow known to be quiescent).  Conversely, because keys
+ * and values in the map are never null, null serves as a reliable
+ * atomic indicator of the current lack of any result.  To
+ * maintain this property, null serves as an implicit basis for
+ * all non-scalar reduction operations. For the double, long, and
+ * int versions, the basis should be one that, when combined with
+ * any other value, returns that other value (more formally, it
+ * should be the identity element for the reduction). Most common
+ * reductions have these properties; for example, computing a sum
+ * with basis 0 or a minimum with basis MAX_VALUE.
+ *
+ * <p>Search and transformation functions provided as arguments
+ * should similarly return null to indicate the lack of any result
+ * (in which case it is not used). In the case of mapped
+ * reductions, this also enables transformations to serve as
+ * filters, returning null (or, in the case of primitive
+ * specializations, the identity basis) if the element should not
+ * be combined. You can create compound transformations and
+ * filterings by composing them yourself under this "null means
+ * there is nothing there now" rule before using them in search or
+ * reduce operations.
+ *
+ * <p>Methods accepting and/or returning Entry arguments maintain
+ * key-value associations. They may be useful for example when
+ * finding the key for the greatest value. Note that "plain" Entry
+ * arguments can be supplied using {@code new
+ * AbstractMap.SimpleEntry(k,v)}.
+ *
+ * <p>Bulk operations may complete abruptly, throwing an
+ * exception encountered in the application of a supplied
+ * function. Bear in mind when handling such exceptions that other
+ * concurrently executing functions could also have thrown
+ * exceptions, or would have done so if the first exception had
+ * not occurred.
+ *
+ * <p>Speedups for parallel compared to sequential forms are common
+ * but not guaranteed.  Parallel operations involving brief functions
+ * on small maps may execute more slowly than sequential forms if the
+ * underlying work to parallelize the computation is more expensive
+ * than the computation itself.  Similarly, parallelization may not
+ * lead to much actual parallelism if all processors are busy
+ * performing unrelated tasks.
+ *
+ * <p>All arguments to all task methods must be non-null.
+ *
  * <p>This class is a member of the
  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  * Java Collections Framework</a>.
@@ -97,735 +264,2373 @@
  * @param <K> the type of keys maintained by this map
  * @param <V> the type of mapped values
  */
-public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
-        implements ConcurrentMap<K, V>, Serializable {
+@SuppressWarnings({"unchecked", "rawtypes", "serial"})
+public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
+    implements ConcurrentMap<K,V>, Serializable {
+
     private static final long serialVersionUID = 7249069246763182397L;
 
     /*
-     * The basic strategy is to subdivide the table among Segments,
-     * each of which itself is a concurrently readable hash table.  To
-     * reduce footprint, all but one segments are constructed only
-     * when first needed (see ensureSegment). To maintain visibility
-     * in the presence of lazy construction, accesses to segments as
-     * well as elements of segment's table must use volatile access,
-     * which is done via Unsafe within methods segmentAt etc
-     * below. These provide the functionality of AtomicReferenceArrays
-     * but reduce the levels of indirection. Additionally,
-     * volatile-writes of table elements and entry "next" fields
-     * within locked operations use the cheaper "lazySet" forms of
-     * writes (via putOrderedObject) because these writes are always
-     * followed by lock releases that maintain sequential consistency
-     * of table updates.
+     * Overview:
      *
-     * Historical note: The previous version of this class relied
-     * heavily on "final" fields, which avoided some volatile reads at
-     * the expense of a large initial footprint.  Some remnants of
-     * that design (including forced construction of segment 0) exist
-     * to ensure serialization compatibility.
+     * The primary design goal of this hash table is to maintain
+     * concurrent readability (typically method get(), but also
+     * iterators and related methods) while minimizing update
+     * contention. Secondary goals are to keep space consumption about
+     * the same or better than java.util.HashMap, and to support high
+     * initial insertion rates on an empty table by many threads.
+     *
+     * Each key-value mapping is held in a Node.  Because Node key
+     * fields can contain special values, they are defined using plain
+     * Object types (not type "K"). This leads to a lot of explicit
+     * casting (and the use of class-wide warning suppressions).  It
+     * also allows some of the public methods to be factored into a
+     * smaller number of internal methods (although sadly not so for
+     * the five variants of put-related operations). The
+     * validation-based approach explained below leads to a lot of
+     * code sprawl because retry-control precludes factoring into
+     * smaller methods.
+     *
+     * The table is lazily initialized to a power-of-two size upon the
+     * first insertion.  Each bin in the table normally contains a
+     * list of Nodes (most often, the list has only zero or one Node).
+     * Table accesses require volatile/atomic reads, writes, and
+     * CASes.  Because there is no other way to arrange this without
+     * adding further indirections, we use intrinsics
+     * (sun.misc.Unsafe) operations.
+     *
+     * We use the top (sign) bit of Node hash fields for control
+     * purposes -- it is available anyway because of addressing
+     * constraints.  Nodes with negative hash fields are forwarding
+     * nodes to either TreeBins or resized tables.  The lower 31 bits
+     * of each normal Node's hash field contain a transformation of
+     * the key's hash code.
+     *
+     * Insertion (via put or its variants) of the first node in an
+     * empty bin is performed by just CASing it to the bin.  This is
+     * by far the most common case for put operations under most
+     * key/hash distributions.  Other update operations (insert,
+     * delete, and replace) require locks.  We do not want to waste
+     * the space required to associate a distinct lock object with
+     * each bin, so instead use the first node of a bin list itself as
+     * a lock. Locking support for these locks relies on builtin
+     * "synchronized" monitors.
+     *
+     * Using the first node of a list as a lock does not by itself
+     * suffice though: When a node is locked, any update must first
+     * validate that it is still the first node after locking it, and
+     * retry if not. Because new nodes are always appended to lists,
+     * once a node is first in a bin, it remains first until deleted
+     * or the bin becomes invalidated (upon resizing).
+     *
+     * The main disadvantage of per-bin locks is that other update
+     * operations on other nodes in a bin list protected by the same
+     * lock can stall, for example when user equals() or mapping
+     * functions take a long time.  However, statistically, under
+     * random hash codes, this is not a common problem.  Ideally, the
+     * frequency of nodes in bins follows a Poisson distribution
+     * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
+     * parameter of about 0.5 on average, given the resizing threshold
+     * of 0.75, although with a large variance because of resizing
+     * granularity. Ignoring variance, the expected occurrences of
+     * list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The
+     * first values are:
+     *
+     * 0:    0.60653066
+     * 1:    0.30326533
+     * 2:    0.07581633
+     * 3:    0.01263606
+     * 4:    0.00157952
+     * 5:    0.00015795
+     * 6:    0.00001316
+     * 7:    0.00000094
+     * 8:    0.00000006
+     * more: less than 1 in ten million
+     *
+     * Lock contention probability for two threads accessing distinct
+     * elements is roughly 1 / (8 * #elements) under random hashes.
+     *
+     * Actual hash code distributions encountered in practice
+     * sometimes deviate significantly from uniform randomness.  This
+     * includes the case when N > (1<<30), so some keys MUST collide.
+     * Similarly for dumb or hostile usages in which multiple keys are
+     * designed to have identical hash codes. Also, although we guard
+     * against the worst effects of this (see method spread), sets of
+     * hashes may differ only in bits that do not impact their bin
+     * index for a given power-of-two mask.  So we use a secondary
+     * strategy that applies when the number of nodes in a bin exceeds
+     * a threshold, and at least one of the keys implements
+     * Comparable.  These TreeBins use a balanced tree to hold nodes
+     * (a specialized form of red-black trees), bounding search time
+     * to O(log N).  Each search step in a TreeBin is at least twice as
+     * slow as in a regular list, but given that N cannot exceed
+     * (1<<64) (before running out of addresses) this bounds search
+     * steps, lock hold times, etc, to reasonable constants (roughly
+     * 100 nodes inspected per operation worst case) so long as keys
+     * are Comparable (which is very common -- String, Long, etc).
+     * TreeBin nodes (TreeNodes) also maintain the same "next"
+     * traversal pointers as regular nodes, so can be traversed in
+     * iterators in the same way.
+     *
+     * The table is resized when occupancy exceeds a percentage
+     * threshold (nominally, 0.75, but see below).  Any thread
+     * noticing an overfull bin may assist in resizing after the
+     * initiating thread allocates and sets up the replacement
+     * array. However, rather than stalling, these other threads may
+     * proceed with insertions etc.  The use of TreeBins shields us
+     * from the worst case effects of overfilling while resizes are in
+     * progress.  Resizing proceeds by transferring bins, one by one,
+     * from the table to the next table. To enable concurrency, the
+     * next table must be (incrementally) prefilled with place-holders
+     * serving as reverse forwarders to the old table.  Because we are
+     * using power-of-two expansion, the elements from each bin must
+     * either stay at same index, or move with a power of two
+     * offset. We eliminate unnecessary node creation by catching
+     * cases where old nodes can be reused because their next fields
+     * won't change.  On average, only about one-sixth of them need
+     * cloning when a table doubles. The nodes they replace will be
+     * garbage collectable as soon as they are no longer referenced by
+     * any reader thread that may be in the midst of concurrently
+     * traversing table.  Upon transfer, the old table bin contains
+     * only a special forwarding node (with hash field "MOVED") that
+     * contains the next table as its key. On encountering a
+     * forwarding node, access and update operations restart, using
+     * the new table.
+     *
+     * Each bin transfer requires its bin lock, which can stall
+     * waiting for locks while resizing. However, because other
+     * threads can join in and help resize rather than contend for
+     * locks, average aggregate waits become shorter as resizing
+     * progresses.  The transfer operation must also ensure that all
+     * accessible bins in both the old and new table are usable by any
+     * traversal.  This is arranged by proceeding from the last bin
+     * (table.length - 1) up towards the first.  Upon seeing a
+     * forwarding node, traversals (see class Traverser) arrange to
+     * move to the new table without revisiting nodes.  However, to
+     * ensure that no intervening nodes are skipped, bin splitting can
+     * only begin after the associated reverse-forwarders are in
+     * place.
+     *
+     * The traversal scheme also applies to partial traversals of
+     * ranges of bins (via an alternate Traverser constructor)
+     * to support partitioned aggregate operations.  Also, read-only
+     * operations give up if ever forwarded to a null table, which
+     * provides support for shutdown-style clearing, which is also not
+     * currently implemented.
+     *
+     * Lazy table initialization minimizes footprint until first use,
+     * and also avoids resizings when the first operation is from a
+     * putAll, constructor with map argument, or deserialization.
+     * These cases attempt to override the initial capacity settings,
+     * but harmlessly fail to take effect in cases of races.
+     *
+     * The element count is maintained using a specialization of
+     * LongAdder. We need to incorporate a specialization rather than
+     * just use a LongAdder in order to access implicit
+     * contention-sensing that leads to creation of multiple
+     * Cells.  The counter mechanics avoid contention on
+     * updates but can encounter cache thrashing if read too
+     * frequently during concurrent access. To avoid reading so often,
+     * resizing under contention is attempted only upon adding to a
+     * bin already holding two or more nodes. Under uniform hash
+     * distributions, the probability of this occurring at threshold
+     * is around 13%, meaning that only about 1 in 8 puts check
+     * threshold (and after resizing, many fewer do so). The bulk
+     * putAll operation further reduces contention by only committing
+     * count updates upon these size checks.
+     *
+     * Maintaining API and serialization compatibility with previous
+     * versions of this class introduces several oddities. Mainly: We
+     * leave untouched but unused constructor arguments refering to
+     * concurrencyLevel. We accept a loadFactor constructor argument,
+     * but apply it only to initial table capacity (which is the only
+     * time that we can guarantee to honor it.) We also declare an
+     * unused "Segment" class that is instantiated in minimal form
+     * only when serializing.
      */
 
     /* ---------------- Constants -------------- */
 
     /**
-     * The default initial capacity for this table,
-     * used when not otherwise specified in a constructor.
+     * The largest possible table capacity.  This value must be
+     * exactly 1<<30 to stay within Java array allocation and indexing
+     * bounds for power of two table sizes, and is further required
+     * because the top two bits of 32bit hash fields are used for
+     * control purposes.
      */
-    static final int DEFAULT_INITIAL_CAPACITY = 16;
+    private static final int MAXIMUM_CAPACITY = 1 << 30;
 
     /**
-     * The default load factor for this table, used when not
-     * otherwise specified in a constructor.
+     * The default initial table capacity.  Must be a power of 2
+     * (i.e., at least 1) and at most MAXIMUM_CAPACITY.
      */
-    static final float DEFAULT_LOAD_FACTOR = 0.75f;
+    private static final int DEFAULT_CAPACITY = 16;
 
     /**
-     * The default concurrency level for this table, used when not
-     * otherwise specified in a constructor.
+     * The largest possible (non-power of two) array size.
+     * Needed by toArray and related methods.
      */
-    static final int DEFAULT_CONCURRENCY_LEVEL = 16;
+    static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 
     /**
-     * The maximum capacity, used if a higher value is implicitly
-     * specified by either of the constructors with arguments.  MUST
-     * be a power of two <= 1<<30 to ensure that entries are indexable
-     * using ints.
+     * The default concurrency level for this table. Unused but
+     * defined for compatibility with previous versions of this class.
      */
-    static final int MAXIMUM_CAPACITY = 1 << 30;
+    private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
 
     /**
-     * The minimum capacity for per-segment tables.  Must be a power
-     * of two, at least two to avoid immediate resizing on next use
-     * after lazy construction.
+     * The load factor for this table. Overrides of this value in
+     * constructors affect only the initial table capacity.  The
+     * actual floating point value isn't normally used -- it is
+     * simpler to use expressions such as {@code n - (n >>> 2)} for
+     * the associated resizing threshold.
      */
-    static final int MIN_SEGMENT_TABLE_CAPACITY = 2;
+    private static final float LOAD_FACTOR = 0.75f;
 
     /**
-     * The maximum number of segments to allow; used to bound
-     * constructor arguments. Must be power of two less than 1 << 24.
+     * The bin count threshold for using a tree rather than list for a
+     * bin.  The value reflects the approximate break-even point for
+     * using tree-based operations.
      */
-    static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
+    private static final int TREE_THRESHOLD = 8;
 
     /**
-     * Number of unsynchronized retries in size and containsValue
-     * methods before resorting to locking. This is used to avoid
-     * unbounded retries if tables undergo continuous modification
-     * which would make it impossible to obtain an accurate result.
+     * Minimum number of rebinnings per transfer step. Ranges are
+     * subdivided to allow multiple resizer threads.  This value
+     * serves as a lower bound to avoid resizers encountering
+     * excessive memory contention.  The value should be at least
+     * DEFAULT_CAPACITY.
      */
-    static final int RETRIES_BEFORE_LOCK = 2;
+    private static final int MIN_TRANSFER_STRIDE = 16;
+
+    /*
+     * Encodings for Node hash fields. See above for explanation.
+     */
+    static final int MOVED     = 0x80000000; // hash field for forwarding nodes
+    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)
+    };
+
+    /**
+     * A padded cell for distributing counts.  Adapted from LongAdder
+     * and Striped64.  See their internal docs for explanation.
+     */
+    @sun.misc.Contended static final class Cell {
+        volatile long value;
+        Cell(long x) { value = x; }
+    }
 
     /* ---------------- Fields -------------- */
 
     /**
-     * A randomizing value associated with this instance that is applied to
-     * hash code of keys to make hash collisions harder to find.
+     * The array of bins. Lazily initialized upon first insertion.
+     * Size is always a power of two. Accessed directly by iterators.
      */
-   private transient final int hashSeed = sun.misc.Hashing.randomHashSeed(this);
+    transient volatile Node<K,V>[] table;
 
     /**
-     * Mask value for indexing into segments. The upper bits of a
-     * key's hash code are used to choose the segment.
+     * The next table to use; non-null only while resizing.
      */
-    final int segmentMask;
+    private transient volatile Node<K,V>[] nextTable;
 
     /**
-     * Shift value for indexing within segments.
+     * Base counter value, used mainly when there is no contention,
+     * but also as a fallback during table initialization
+     * races. Updated via CAS.
      */
-    final int segmentShift;
+    private transient volatile long baseCount;
 
     /**
-     * The segments, each of which is a specialized hash table.
+     * Table initialization and resizing control.  When negative, the
+     * table is being initialized or resized: -1 for initialization,
+     * else -(1 + the number of active resizing threads).  Otherwise,
+     * when table is null, holds the initial table size to use upon
+     * creation, or 0 for default. After initialization, holds the
+     * next element count value upon which to resize the table.
      */
-    final Segment<K,V>[] segments;
-
-    transient Set<K> keySet;
-    transient Set<Map.Entry<K,V>> entrySet;
-    transient Collection<V> values;
+    private transient volatile int sizeCtl;
 
     /**
-     * ConcurrentHashMap list entry. Note that this is never exported
-     * out as a user-visible Map.Entry.
+     * The next table index (plus one) to split while resizing.
      */
-    static final class HashEntry<K,V> {
+    private transient volatile int transferIndex;
+
+    /**
+     * The least available table index to split while resizing.
+     */
+    private transient volatile int transferOrigin;
+
+    /**
+     * Spinlock (locked via CAS) used when resizing and/or creating Cells.
+     */
+    private transient volatile int cellsBusy;
+
+    /**
+     * Table of counter cells. When non-null, size is a power of 2.
+     */
+    private transient volatile Cell[] counterCells;
+
+    // views
+    private transient KeySetView<K,V> keySet;
+    private transient ValuesView<K,V> values;
+    private transient EntrySetView<K,V> entrySet;
+
+    /* ---------------- Table element access -------------- */
+
+    /*
+     * Volatile access methods are used for table elements as well as
+     * elements of in-progress next table while resizing.  Uses are
+     * null checked by callers, and implicitly bounds-checked, relying
+     * on the invariants that tab arrays have non-zero size, and all
+     * indices are masked with (tab.length - 1) which is never
+     * negative and always less than length. Note that, to be correct
+     * wrt arbitrary concurrency errors by users, bounds checks must
+     * operate on local variables, which accounts for some odd-looking
+     * inline assignments below.
+     */
+
+    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
+        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
+    }
+
+    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
+                                        Node<K,V> c, Node<K,V> v) {
+        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
+    }
+
+    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
+        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
+    }
+
+    /* ---------------- Nodes -------------- */
+
+    /**
+     * Key-value entry.  This class is never exported out as a
+     * user-mutable Map.Entry (i.e., one supporting setValue; see
+     * MapEntry below), but can be used for read-only traversals used
+     * in bulk tasks.  Nodes with a hash field of MOVED are special,
+     * and do not contain user keys or values (and are never
+     * exported).  Otherwise, keys and vals are never null.
+     */
+    static class Node<K,V> implements Map.Entry<K,V> {
         final int hash;
-        final K key;
-        volatile V value;
-        volatile HashEntry<K,V> next;
-
-        HashEntry(int hash, K key, V value, HashEntry<K,V> next) {
+        final Object key;
+        volatile V val;
+        Node<K,V> next;
+
+        Node(int hash, Object key, V val, Node<K,V> next) {
             this.hash = hash;
             this.key = key;
-            this.value = value;
+            this.val = val;
             this.next = next;
         }
 
+        public final K getKey()       { return (K)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)));
+        }
+    }
+
+    /**
+     * Exported Entry for EntryIterator
+     */
+    static final class MapEntry<K,V> implements Map.Entry<K,V> {
+        final K key; // non-null
+        V val;       // non-null
+        final ConcurrentHashMap<K,V> map;
+        MapEntry(K key, V val, ConcurrentHashMap<K,V> 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 next field with volatile write semantics.  (See above
-         * about use of putOrderedObject.)
+         * 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.
          */
-        final void setNext(HashEntry<K,V> n) {
-            UNSAFE.putOrderedObject(this, nextOffset, n);
+        public V setValue(V value) {
+            if (value == null) throw new NullPointerException();
+            V v = val;
+            val = value;
+            map.put(key, value);
+            return v;
         }
-
-        // Unsafe mechanics
-        static final sun.misc.Unsafe UNSAFE;
-        static final long nextOffset;
-        static {
-            try {
-                UNSAFE = sun.misc.Unsafe.getUnsafe();
-                Class<?> k = HashEntry.class;
-                nextOffset = UNSAFE.objectFieldOffset
-                    (k.getDeclaredField("next"));
-            } catch (Exception e) {
-                throw new Error(e);
+    }
+
+
+    /* ---------------- TreeBins -------------- */
+
+    /**
+     * Nodes for use in TreeBins
+     */
+    static final class TreeNode<K,V> extends Node<K,V> {
+        TreeNode<K,V> parent;  // red-black tree links
+        TreeNode<K,V> left;
+        TreeNode<K,V> right;
+        TreeNode<K,V> prev;    // needed to unlink next upon deletion
+        boolean red;
+
+        TreeNode(int hash, Object key, V val, Node<K,V> next,
+                 TreeNode<K,V> parent) {
+            super(hash, key, val, next);
+            this.parent = parent;
+        }
+    }
+
+    /**
+     * Returns a Class for the given type of the form "class C
+     * implements Comparable<C>", if one exists, else null.  See below
+     * for explanation.
+     */
+    static Class<?> comparableClassFor(Class<?> c) {
+        Class<?> s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
+        if (c == String.class) // bypass checks
+            return c;
+        if (c != null && (cmpc = Comparable.class).isAssignableFrom(c)) {
+            while (cmpc.isAssignableFrom(s = c.getSuperclass()))
+                c = s; // find topmost comparable class
+            if ((ts = c.getGenericInterfaces()) != null) {
+                for (int i = 0; i < ts.length; ++i) {
+                    if (((t = ts[i]) instanceof ParameterizedType) &&
+                        ((p = (ParameterizedType)t).getRawType() == cmpc) &&
+                        (as = p.getActualTypeArguments()) != null &&
+                        as.length == 1 && as[0] == c) // type arg is c
+                        return c;
+                }
             }
         }
+        return null;
     }
 
     /**
-     * Gets the ith element of given table (if nonnull) with volatile
-     * read semantics. Note: This is manually integrated into a few
-     * performance-sensitive methods to reduce call overhead.
+     * A specialized form of red-black tree for use in bins
+     * whose size exceeds a threshold.
+     *
+     * TreeBins use a special form of comparison for search and
+     * related operations (which is the main reason we cannot use
+     * existing collections such as TreeMaps). TreeBins contain
+     * Comparable elements, but may contain others, as well as
+     * elements that are Comparable but not necessarily Comparable
+     * for the same T, so we cannot invoke compareTo among them. To
+     * handle this, the tree is ordered primarily by hash value, then
+     * by Comparable.compareTo order if applicable.  On lookup at a
+     * node, if elements are not comparable or compare as 0 then both
+     * left and right children may need to be searched in the case of
+     * tied hash values. (This corresponds to the full list search
+     * that would be necessary if all elements were non-Comparable and
+     * had tied hashes.)  The red-black balancing code is updated from
+     * pre-jdk-collections
+     * (http://gee.cs.oswego.edu/dl/classes/collections/RBCell.java)
+     * based in turn on Cormen, Leiserson, and Rivest "Introduction to
+     * Algorithms" (CLR).
+     *
+     * TreeBins also maintain a separate locking discipline than
+     * regular bins. Because they are forwarded via special MOVED
+     * nodes at bin heads (which can never change once established),
+     * we cannot use those nodes as locks. Instead, TreeBin extends
+     * StampedLock to support a form of read-write lock. For update
+     * operations and table validation, the exclusive form of lock
+     * behaves in the same way as bin-head locks. However, lookups use
+     * shared read-lock mechanics to allow multiple readers in the
+     * absence of writers.  Additionally, these lookups do not ever
+     * block: While the lock is not available, they proceed along the
+     * slow traversal path (via next-pointers) until the lock becomes
+     * available or the list is exhausted, whichever comes
+     * first. These cases are not fast, but maximize aggregate
+     * expected throughput.
      */
-    @SuppressWarnings("unchecked")
-    static final <K,V> HashEntry<K,V> entryAt(HashEntry<K,V>[] tab, int i) {
-        return (tab == null) ? null :
-            (HashEntry<K,V>) UNSAFE.getObjectVolatile
-            (tab, ((long)i << TSHIFT) + TBASE);
-    }
-
-    /**
-     * Sets the ith element of given table, with volatile write
-     * semantics. (See above about use of putOrderedObject.)
-     */
-    static final <K,V> void setEntryAt(HashEntry<K,V>[] tab, int i,
-                                       HashEntry<K,V> e) {
-        UNSAFE.putOrderedObject(tab, ((long)i << TSHIFT) + TBASE, e);
-    }
-
-    /**
-     * Applies a supplemental hash function to a given hashCode, which
-     * defends against poor quality hash functions.  This is critical
-     * because ConcurrentHashMap uses power-of-two length hash tables,
-     * that otherwise encounter collisions for hashCodes that do not
-     * differ in lower or upper bits.
-     */
-    private int hash(Object k) {
-        if (k instanceof String) {
-            return ((String) k).hash32();
+    static final class TreeBin<K,V> extends StampedLock {
+        private static final long serialVersionUID = 2249069246763182397L;
+        transient TreeNode<K,V> root;  // root of tree
+        transient TreeNode<K,V> first; // head of next-pointer list
+
+        /** From CLR */
+        private void rotateLeft(TreeNode<K,V> p) {
+            if (p != null) {
+                TreeNode<K,V> r = p.right, pp, rl;
+                if ((rl = p.right = r.left) != null)
+                    rl.parent = p;
+                if ((pp = r.parent = p.parent) == null)
+                    root = r;
+                else if (pp.left == p)
+                    pp.left = r;
+                else
+                    pp.right = r;
+                r.left = p;
+                p.parent = r;
+            }
         }
 
-        int h = hashSeed ^ k.hashCode();
-
-        // Spread bits to regularize both segment and index locations,
-        // using variant of single-word Wang/Jenkins hash.
-        h += (h <<  15) ^ 0xffffcd7d;
-        h ^= (h >>> 10);
-        h += (h <<   3);
-        h ^= (h >>>  6);
-        h += (h <<   2) + (h << 14);
-        return h ^ (h >>> 16);
-    }
-
-    /**
-     * Segments are specialized versions of hash tables.  This
-     * subclasses from ReentrantLock opportunistically, just to
-     * simplify some locking and avoid separate construction.
-     */
-    static final class Segment<K,V> extends ReentrantLock implements Serializable {
-        /*
-         * Segments maintain a table of entry lists that are always
-         * kept in a consistent state, so can be read (via volatile
-         * reads of segments and tables) without locking.  This
-         * requires replicating nodes when necessary during table
-         * resizing, so the old lists can be traversed by readers
-         * still using old version of table.
-         *
-         * This class defines only mutative methods requiring locking.
-         * Except as noted, the methods of this class perform the
-         * per-segment versions of ConcurrentHashMap methods.  (Other
-         * methods are integrated directly into ConcurrentHashMap
-         * methods.) These mutative methods use a form of controlled
-         * spinning on contention via methods scanAndLock and
-         * scanAndLockForPut. These intersperse tryLocks with
-         * traversals to locate nodes.  The main benefit is to absorb
-         * cache misses (which are very common for hash tables) while
-         * obtaining locks so that traversal is faster once
-         * acquired. We do not actually use the found nodes since they
-         * must be re-acquired under lock anyway to ensure sequential
-         * consistency of updates (and in any case may be undetectably
-         * stale), but they will normally be much faster to re-locate.
-         * Also, scanAndLockForPut speculatively creates a fresh node
-         * to use in put if no node is found.
+        /** From CLR */
+        private void rotateRight(TreeNode<K,V> p) {
+            if (p != null) {
+                TreeNode<K,V> l = p.left, pp, lr;
+                if ((lr = p.left = l.right) != null)
+                    lr.parent = p;
+                if ((pp = l.parent = p.parent) == null)
+                    root = l;
+                else if (pp.right == p)
+                    pp.right = l;
+                else
+                    pp.left = l;
+                l.right = p;
+                p.parent = l;
+            }
+        }
+
+        /**
+         * Returns the TreeNode (or null if not found) for the given key
+         * starting at given root.
          */
-
-        private static final long serialVersionUID = 2249069246763182397L;
+        final TreeNode<K,V> getTreeNode(int h, Object k, TreeNode<K,V> p,
+                                        Class<?> cc) {
+            while (p != null) {
+                int dir, ph; Object pk; Class<?> pc;
+                if ((ph = p.hash) != h)
+                    dir = (h < ph) ? -1 : 1;
+                else if ((pk = p.key) == k || k.equals(pk))
+                    return p;
+                else if (cc == null || pk == null ||
+                         ((pc = pk.getClass()) != cc &&
+                          comparableClassFor(pc) != cc) ||
+                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
+                    TreeNode<K,V> r, pr; // check both sides
+                    if ((pr = p.right) != null &&
+                        (r = getTreeNode(h, k, pr, cc)) != null)
+                        return r;
+                    else // continue left
+                        dir = -1;
+                }
+                p = (dir > 0) ? p.right : p.left;
+            }
+            return null;
+        }
 
         /**
-         * The maximum number of times to tryLock in a prescan before
-         * possibly blocking on acquire in preparation for a locked
-         * segment operation. On multiprocessors, using a bounded
-         * number of retries maintains cache acquired while locating
-         * nodes.
+         * Wrapper for getTreeNode used by CHM.get. Tries to obtain
+         * read-lock to call getTreeNode, but during failure to get
+         * lock, searches along next links.
          */
-        static final int MAX_SCAN_RETRIES =
-            Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
+        final V getValue(int h, Object k) {
+            Class<?> cc = comparableClassFor(k.getClass());
+            Node<K,V> r = null;
+            for (Node<K,V> e = first; e != null; e = e.next) {
+                long s;
+                if ((s = tryReadLock()) != 0L) {
+                    try {
+                        r = getTreeNode(h, k, root, cc);
+                    } finally {
+                        unlockRead(s);
+                    }
+                    break;
+                }
+                else if (e.hash == h && k.equals(e.key)) {
+                    r = e;
+                    break;
+                }
+            }
+            return r == null ? null : r.val;
+        }
 
         /**
-         * The per-segment table. Elements are accessed via
-         * entryAt/setEntryAt providing volatile semantics.
+         * Finds or adds a node.
+         * @return null if added
          */
-        transient volatile HashEntry<K,V>[] table;
-
-        /**
-         * The number of elements. Accessed only either within locks
-         * or among other volatile reads that maintain visibility.
-         */
-        transient int count;
-
-        /**
-         * The total number of mutative operations in this segment.
-         * Even though this may overflows 32 bits, it provides
-         * sufficient accuracy for stability checks in CHM isEmpty()
-         * and size() methods.  Accessed only either within locks or
-         * among other volatile reads that maintain visibility.
-         */
-        transient int modCount;
-
-        /**
-         * The table is rehashed when its size exceeds this threshold.
-         * (The value of this field is always {@code (int)(capacity *
-         * loadFactor)}.)
-         */
-        transient int threshold;
-
-        /**
-         * The load factor for the hash table.  Even though this value
-         * is same for all segments, it is replicated to avoid needing
-         * links to outer object.
-         * @serial
-         */
-        final float loadFactor;
-
-        Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
-            this.loadFactor = lf;
-            this.threshold = threshold;
-            this.table = tab;
-        }
-
-        final V put(K key, int hash, V value, boolean onlyIfAbsent) {
-            HashEntry<K,V> node = tryLock() ? null :
-                scanAndLockForPut(key, hash, value);
-            V oldValue;
-            try {
-                HashEntry<K,V>[] tab = table;
-                int index = (tab.length - 1) & hash;
-                HashEntry<K,V> first = entryAt(tab, index);
-                for (HashEntry<K,V> e = first;;) {
-                    if (e != null) {
-                        K k;
-                        if ((k = e.key) == key ||
-                            (e.hash == hash && key.equals(k))) {
-                            oldValue = e.value;
-                            if (!onlyIfAbsent) {
-                                e.value = value;
-                                ++modCount;
+        final TreeNode<K,V> putTreeNode(int h, Object k, V v) {
+            Class<?> cc = comparableClassFor(k.getClass());
+            TreeNode<K,V> pp = root, p = null;
+            int dir = 0;
+            while (pp != null) { // find existing node or leaf to insert at
+                int ph; Object pk; Class<?> pc;
+                p = pp;
+                if ((ph = p.hash) != h)
+                    dir = (h < ph) ? -1 : 1;
+                else if ((pk = p.key) == k || k.equals(pk))
+                    return p;
+                else if (cc == null || pk == null ||
+                         ((pc = pk.getClass()) != cc &&
+                          comparableClassFor(pc) != cc) ||
+                         (dir = ((Comparable<Object>)k).compareTo(pk)) == 0) {
+                    TreeNode<K,V> r, pr;
+                    if ((pr = p.right) != null &&
+                        (r = getTreeNode(h, k, pr, cc)) != null)
+                        return r;
+                    else // continue left
+                        dir = -1;
+                }
+                pp = (dir > 0) ? p.right : p.left;
+            }
+
+            TreeNode<K,V> f = first;
+            TreeNode<K,V> x = first = new TreeNode<K,V>(h, k, v, f, p);
+            if (p == null)
+                root = x;
+            else { // attach and rebalance; adapted from CLR
+                if (f != null)
+                    f.prev = x;
+                if (dir <= 0)
+                    p.left = x;
+                else
+                    p.right = x;
+                x.red = true;
+                for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
+                    if ((xp = x.parent) == null) {
+                        (root = x).red = false;
+                        break;
+                    }
+                    else if (!xp.red || (xpp = xp.parent) == null) {
+                        TreeNode<K,V> r = root;
+                        if (r != null && r.red)
+                            r.red = false;
+                        break;
+                    }
+                    else if ((xppl = xpp.left) == xp) {
+                        if ((xppr = xpp.right) != null && xppr.red) {
+                            xppr.red = false;
+                            xp.red = false;
+                            xpp.red = true;
+                            x = xpp;
+                        }
+                        else {
+                            if (x == xp.right) {
+                                rotateLeft(x = xp);
+                                xpp = (xp = x.parent) == null ? null : xp.parent;
                             }
-                            break;
+                            if (xp != null) {
+                                xp.red = false;
+                                if (xpp != null) {
+                                    xpp.red = true;
+                                    rotateRight(xpp);
+                                }
+                            }
                         }
-                        e = e.next;
                     }
                     else {
-                        if (node != null)
-                            node.setNext(first);
-                        else
-                            node = new HashEntry<K,V>(hash, key, value, first);
-                        int c = count + 1;
-                        if (c > threshold && tab.length < MAXIMUM_CAPACITY)
-                            rehash(node);
-                        else
-                            setEntryAt(tab, index, node);
-                        ++modCount;
-                        count = c;
-                        oldValue = null;
-                        break;
-                    }
-                }
-            } finally {
-                unlock();
-            }
-            return oldValue;
-        }
-
-        /**
-         * Doubles size of table and repacks entries, also adding the
-         * given node to new table
-         */
-        @SuppressWarnings("unchecked")
-        private void rehash(HashEntry<K,V> node) {
-            /*
-             * Reclassify nodes in each list to new table.  Because we
-             * are using power-of-two expansion, the elements from
-             * each bin must either stay at same index, or move with a
-             * power of two offset. We eliminate unnecessary node
-             * creation by catching cases where old nodes can be
-             * reused because their next fields won't change.
-             * Statistically, at the default threshold, only about
-             * one-sixth of them need cloning when a table
-             * doubles. The nodes they replace will be garbage
-             * collectable as soon as they are no longer referenced by
-             * any reader thread that may be in the midst of
-             * concurrently traversing table. Entry accesses use plain
-             * array indexing because they are followed by volatile
-             * table write.
-             */
-            HashEntry<K,V>[] oldTable = table;
-            int oldCapacity = oldTable.length;
-            int newCapacity = oldCapacity << 1;
-            threshold = (int)(newCapacity * loadFactor);
-            HashEntry<K,V>[] newTable =
-                (HashEntry<K,V>[]) new HashEntry<?,?>[newCapacity];
-            int sizeMask = newCapacity - 1;
-            for (int i = 0; i < oldCapacity ; i++) {
-                HashEntry<K,V> e = oldTable[i];
-                if (e != null) {
-                    HashEntry<K,V> next = e.next;
-                    int idx = e.hash & sizeMask;
-                    if (next == null)   //  Single node on list
-                        newTable[idx] = e;
-                    else { // Reuse consecutive sequence at same slot
-                        HashEntry<K,V> lastRun = e;
-                        int lastIdx = idx;
-                        for (HashEntry<K,V> last = next;
-                             last != null;
-                             last = last.next) {
-                            int k = last.hash & sizeMask;
-                            if (k != lastIdx) {
-                                lastIdx = k;
-                                lastRun = last;
+                        if (xppl != null && xppl.red) {
+                            xppl.red = false;
+                            xp.red = false;
+                            xpp.red = true;
+                            x = xpp;
+                        }
+                        else {
+                            if (x == xp.left) {
+                                rotateRight(x = xp);
+                                xpp = (xp = x.parent) == null ? null : xp.parent;
                             }
-                        }
-                        newTable[lastIdx] = lastRun;
-                        // Clone remaining nodes
-                        for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
-                            V v = p.value;
-                            int h = p.hash;
-                            int k = h & sizeMask;
-                            HashEntry<K,V> n = newTable[k];
-                            newTable[k] = new HashEntry<K,V>(h, p.key, v, n);
+                            if (xp != null) {
+                                xp.red = false;
+                                if (xpp != null) {
+                                    xpp.red = true;
+                                    rotateLeft(xpp);
+                                }
+                            }
                         }
                     }
                 }
             }
-            int nodeIndex = node.hash & sizeMask; // add the new node
-            node.setNext(newTable[nodeIndex]);
-            newTable[nodeIndex] = node;
-            table = newTable;
+            assert checkInvariants();
+            return null;
         }
 
         /**
-         * Scans for a node containing given key while trying to
-         * acquire lock, creating and returning one if not found. Upon
-         * return, guarantees that lock is held. UNlike in most
-         * methods, calls to method equals are not screened: Since
-         * traversal speed doesn't matter, we might as well help warm
-         * up the associated code and accesses as well.
-         *
-         * @return a new node if key not found, else 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.
          */
-        private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {
-            HashEntry<K,V> first = entryForHash(this, hash);
-            HashEntry<K,V> e = first;
-            HashEntry<K,V> node = null;
-            int retries = -1; // negative while locating node
-            while (!tryLock()) {
-                HashEntry<K,V> f; // to recheck first below
-                if (retries < 0) {
-                    if (e == null) {
-                        if (node == null) // speculatively create node
-                            node = new HashEntry<K,V>(hash, key, value, null);
-                        retries = 0;
+        final void deleteTreeNode(TreeNode<K,V> p) {
+            TreeNode<K,V> next = (TreeNode<K,V>)p.next;
+            TreeNode<K,V> pred = p.prev;  // unlink traversal pointers
+            if (pred == null)
+                first = next;
+            else
+                pred.next = next;
+            if (next != null)
+                next.prev = pred;
+            else if (pred == null) {
+                root = null;
+                return;
+            }
+            TreeNode<K,V> replacement;
+            TreeNode<K,V> pl = p.left;
+            TreeNode<K,V> pr = p.right;
+            if (pl != null && pr != null) {
+                TreeNode<K,V> 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<K,V> sr = s.right;
+                TreeNode<K,V> pp = p.parent;
+                if (s == pr) { // p was s's direct parent
+                    p.parent = s;
+                    s.right = p;
+                }
+                else {
+                    TreeNode<K,V> sp = s.parent;
+                    if ((p.parent = sp) != null) {
+                        if (s == sp.left)
+                            sp.left = p;
+                        else
+                            sp.right = p;
                     }
-                    else if (key.equals(e.key))
-                        retries = 0;
-                    else
-                        e = e.next;
+                    if ((s.right = pr) != null)
+                        pr.parent = s;
                 }
-                else if (++retries > MAX_SCAN_RETRIES) {
-                    lock();
+                p.left = null;
+                if ((p.right = sr) != null)
+                    sr.parent = p;
+                if ((s.left = pl) != null)
+                    pl.parent = s;
+                if ((s.parent = pp) == null)
+                    root = 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<K,V> pp = replacement.parent = p.parent;
+                if (pp == null)
+                    root = replacement;
+                else if (p == pp.left)
+                    pp.left = replacement;
+                else
+                    pp.right = replacement;
+                p.left = p.right = p.parent = null;
+            }
+            if (!p.red) { // rebalance, from CLR
+                for (TreeNode<K,V> x = replacement; x != null; ) {
+                    TreeNode<K,V> xp, xpl, xpr;
+                    if (x.red || (xp = x.parent) == null) {
+                        x.red = false;
+                        break;
+                    }
+                    else if ((xpl = xp.left) == x) {
+                        if ((xpr = xp.right) != null && xpr.red) {
+                            xpr.red = false;
+                            xp.red = true;
+                            rotateLeft(xp);
+                            xpr = (xp = x.parent) == null ? null : xp.right;
+                        }
+                        if (xpr == null)
+                            x = xp;
+                        else {
+                            TreeNode<K,V> 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;
+                                    rotateRight(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;
+                                    rotateLeft(xp);
+                                }
+                                x = root;
+                            }
+                        }
+                    }
+                    else { // symmetric
+                        if (xpl != null && xpl.red) {
+                            xpl.red = false;
+                            xp.red = true;
+                            rotateRight(xp);
+                            xpl = (xp = x.parent) == null ? null : xp.left;
+                        }
+                        if (xpl == null)
+                            x = xp;
+                        else {
+                            TreeNode<K,V> 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;
+                                    rotateLeft(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;
+                                    rotateRight(xp);
+                                }
+                                x = root;
+                            }
+                        }
+                    }
+                }
+            }
+            if (p == replacement) {  // detach pointers
+                TreeNode<K,V> pp;
+                if ((pp = p.parent) != null) {
+                    if (p == pp.left)
+                        pp.left = null;
+                    else if (p == pp.right)
+                        pp.right = null;
+                    p.parent = null;
+                }
+            }
+            assert checkInvariants();
+        }
+
+        /**
+         * Checks linkage and balance invariants at root
+         */
+        final boolean checkInvariants() {
+            TreeNode<K,V> r = root;
+            if (r == null)
+                return (first == null);
+            else
+                return (first != null) && checkTreeNode(r);
+        }
+
+        /**
+         * Recursive invariant check
+         */
+        final boolean checkTreeNode(TreeNode<K,V> t) {
+            TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
+                tb = t.prev, tn = (TreeNode<K,V>)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 && !checkTreeNode(tl))
+                return false;
+            if (tr != null && !checkTreeNode(tr))
+                return false;
+            return true;
+        }
+    }
+
+    /* ---------------- Collision reduction methods -------------- */
+
+    /**
+     * Spreads higher bits to lower, and also forces top bit to 0.
+     * Because the table uses power-of-two masking, sets of hashes
+     * that vary only in bits above the current mask will always
+     * collide. (Among known examples are sets of Float keys holding
+     * consecutive whole numbers in small tables.)  To counter this,
+     * we apply a transform that spreads the impact of higher bits
+     * downward. There is a tradeoff between speed, utility, and
+     * quality of bit-spreading. Because many common sets of hashes
+     * are already reasonably distributed across bits (so don't benefit
+     * from spreading), and because we use trees to handle large sets
+     * of collisions in bins, we don't need excessively high quality.
+     */
+    private static final int spread(int h) {
+        h ^= (h >>> 18) ^ (h >>> 12);
+        return (h ^ (h >>> 10)) & HASH_BITS;
+    }
+
+    /**
+     * Replaces a list bin with a tree bin if key is comparable.  Call
+     * only when locked.
+     */
+    private final void replaceWithTreeBin(Node<K,V>[] tab, int index, Object key) {
+        if (tab != null && comparableClassFor(key.getClass()) != null) {
+            TreeBin<K,V> t = new TreeBin<K,V>();
+            for (Node<K,V> e = tabAt(tab, index); e != null; e = e.next)
+                t.putTreeNode(e.hash, e.key, e.val);
+            setTabAt(tab, index, new Node<K,V>(MOVED, t, null, null));
+        }
+    }
+
+    /* ---------------- Internal access and update methods -------------- */
+
+    /** Implementation for get and containsKey */
+    private final V internalGet(Object k) {
+        int h = spread(k.hashCode());
+        V v = null;
+        Node<K,V>[] tab; Node<K,V> e;
+        if ((tab = table) != null &&
+            (e = tabAt(tab, (tab.length - 1) & h)) != null) {
+            for (;;) {
+                int eh; Object ek;
+                if ((eh = e.hash) < 0) {
+                    if ((ek = e.key) instanceof TreeBin) { // search TreeBin
+                        v = ((TreeBin<K,V>)ek).getValue(h, k);
+                        break;
+                    }
+                    else if (!(ek instanceof Node[]) ||    // try new table
+                             (e = tabAt(tab = (Node<K,V>[])ek,
+                                        (tab.length - 1) & h)) == null)
+                        break;
+                }
+                else if (eh == h && ((ek = e.key) == k || k.equals(ek))) {
+                    v = e.val;
                     break;
                 }
-                else if ((retries & 1) == 0 &&
-                         (f = entryForHash(this, hash)) != first) {
-                    e = first = f; // re-traverse if entry changed
-                    retries = -1;
+                else if ((e = e.next) == null)
+                    break;
+            }
+        }
+        return v;
+    }
+
+    /**
+     * Implementation for the four public remove/replace methods:
+     * Replaces node value with v, conditional upon match of cv if
+     * non-null.  If resulting value is null, delete.
+     */
+    private final V internalReplace(Object k, V v, Object cv) {
+        int h = spread(k.hashCode());
+        V oldVal = null;
+        for (Node<K,V>[] tab = table;;) {
+            Node<K,V> f; int i, fh; Object fk;
+            if (tab == null ||
+                (f = tabAt(tab, i = (tab.length - 1) & h)) == null)
+                break;
+            else if ((fh = f.hash) < 0) {
+                if ((fk = f.key) instanceof TreeBin) {
+                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
+                    long stamp = t.writeLock();
+                    boolean validated = false;
+                    boolean deleted = false;
+                    try {
+                        if (tabAt(tab, i) == f) {
+                            validated = true;
+                            Class<?> cc = comparableClassFor(k.getClass());
+                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
+                            if (p != null) {
+                                V pv = p.val;
+                                if (cv == null || cv == pv || cv.equals(pv)) {
+                                    oldVal = pv;
+                                    if (v != null)
+                                        p.val = v;
+                                    else {
+                                        deleted = true;
+                                        t.deleteTreeNode(p);
+                                    }
+                                }
+                            }
+                        }
+                    } finally {
+                        t.unlockWrite(stamp);
+                    }
+                    if (validated) {
+                        if (deleted)
+                            addCount(-1L, -1);
+                        break;
+                    }
                 }
+                else
+                    tab = (Node<K,V>[])fk;
             }
-            return node;
-        }
-
-        /**
-         * Scans for a node containing the given key while trying to
-         * acquire lock for a remove or replace operation. Upon
-         * return, guarantees that lock is held.  Note that we must
-         * lock even if the key is not found, to ensure sequential
-         * consistency of updates.
-         */
-        private void scanAndLock(Object key, int hash) {
-            // similar to but simpler than scanAndLockForPut
-            HashEntry<K,V> first = entryForHash(this, hash);
-            HashEntry<K,V> e = first;
-            int retries = -1;
-            while (!tryLock()) {
-                HashEntry<K,V> f;
-                if (retries < 0) {
-                    if (e == null || key.equals(e.key))
-                        retries = 0;
-                    else
-                        e = e.next;
+            else {
+                boolean validated = false;
+                boolean deleted = false;
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        validated = true;
+                        for (Node<K,V> e = f, pred = null;;) {
+                            Object ek;
+                            if (e.hash == h &&
+                                ((ek = e.key) == k || k.equals(ek))) {
+                                V ev = e.val;
+                                if (cv == null || cv == ev || cv.equals(ev)) {
+                                    oldVal = ev;
+                                    if (v != null)
+                                        e.val = v;
+                                    else {
+                                        deleted = true;
+                                        Node<K,V> 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 (++retries > MAX_SCAN_RETRIES) {
-                    lock();
+                if (validated) {
+                    if (deleted)
+                        addCount(-1L, -1);
                     break;
                 }
-                else if ((retries & 1) == 0 &&
-                         (f = entryForHash(this, hash)) != first) {
-                    e = first = f;
-                    retries = -1;
-                }
             }
         }
-
-        /**
-         * Remove; match on key only if value null, else match both.
-         */
-        final V remove(Object key, int hash, Object value) {
-            if (!tryLock())
-                scanAndLock(key, hash);
-            V oldValue = null;
-            try {
-                HashEntry<K,V>[] tab = table;
-                int index = (tab.length - 1) & hash;
-                HashEntry<K,V> e = entryAt(tab, index);
-                HashEntry<K,V> pred = null;
-                while (e != null) {
-                    K k;
-                    HashEntry<K,V> next = e.next;
-                    if ((k = e.key) == key ||
-                        (e.hash == hash && key.equals(k))) {
-                        V v = e.value;
-                        if (value == null || value == v || value.equals(v)) {
-                            if (pred == null)
-                                setEntryAt(tab, index, next);
-                            else
-                                pred.setNext(next);
-                            ++modCount;
-                            --count;
-                            oldValue = v;
+        return oldVal;
+    }
+
+    /*
+     * Internal versions of insertion methods
+     * All have the same basic structure as the first (internalPut):
+     *  1. If table uninitialized, create
+     *  2. If bin empty, try to CAS new node
+     *  3. If bin stale, use new table
+     *  4. if bin converted to TreeBin, validate and relay to TreeBin methods
+     *  5. Lock and validate; if valid, scan and add or update
+     *
+     * The putAll method differs mainly in attempting to pre-allocate
+     * enough table space, and also more lazily performs count updates
+     * and checks.
+     *
+     * Most of the function-accepting methods can't be factored nicely
+     * because they require different functional forms, so instead
+     * sprawl out similar mechanics.
+     */
+
+    /** Implementation for put and putIfAbsent */
+    private final V internalPut(K k, V v, boolean onlyIfAbsent) {
+        if (k == null || v == null) throw new NullPointerException();
+        int h = spread(k.hashCode());
+        int len = 0;
+        for (Node<K,V>[] tab = table;;) {
+            int i, fh; Node<K,V> f; Object fk;
+            if (tab == null)
+                tab = initTable();
+            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
+                if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null)))
+                    break;                   // no lock when adding to empty bin
+            }
+            else if ((fh = f.hash) < 0) {
+                if ((fk = f.key) instanceof TreeBin) {
+                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
+                    long stamp = t.writeLock();
+                    V oldVal = null;
+                    try {
+                        if (tabAt(tab, i) == f) {
+                            len = 2;
+                            TreeNode<K,V> p = t.putTreeNode(h, k, v);
+                            if (p != null) {
+                                oldVal = p.val;
+                                if (!onlyIfAbsent)
+                                    p.val = v;
+                            }
                         }
-                        break;
+                    } finally {
+                        t.unlockWrite(stamp);
                     }
-                    pred = e;
-                    e = next;
-                }
-            } finally {
-                unlock();
-            }
-            return oldValue;
-        }
-
-        final boolean replace(K key, int hash, V oldValue, V newValue) {
-            if (!tryLock())
-                scanAndLock(key, hash);
-            boolean replaced = false;
-            try {
-                HashEntry<K,V> e;
-                for (e = entryForHash(this, hash); e != null; e = e.next) {
-                    K k;
-                    if ((k = e.key) == key ||
-                        (e.hash == hash && key.equals(k))) {
-                        if (oldValue.equals(e.value)) {
-                            e.value = newValue;
-                            ++modCount;
-                            replaced = true;
-                        }
+                    if (len != 0) {
+                        if (oldVal != null)
+                            return oldVal;
                         break;
                     }
                 }
-            } finally {
-                unlock();
+                else
+                    tab = (Node<K,V>[])fk;
             }
-            return replaced;
+            else {
+                V oldVal = null;
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        len = 1;
+                        for (Node<K,V> e = f;; ++len) {
+                            Object ek;
+                            if (e.hash == h &&
+                                ((ek = e.key) == k || k.equals(ek))) {
+                                oldVal = e.val;
+                                if (!onlyIfAbsent)
+                                    e.val = v;
+                                break;
+                            }
+                            Node<K,V> last = e;
+                            if ((e = e.next) == null) {
+                                last.next = new Node<K,V>(h, k, v, null);
+                                if (len > TREE_THRESHOLD)
+                                    replaceWithTreeBin(tab, i, k);
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (len != 0) {
+                    if (oldVal != null)
+                        return oldVal;
+                    break;
+                }
+            }
         }
-
-        final V replace(K key, int hash, V value) {
-            if (!tryLock())
-                scanAndLock(key, hash);
-            V oldValue = null;
-            try {
-                HashEntry<K,V> e;
-                for (e = entryForHash(this, hash); e != null; e = e.next) {
-                    K k;
-                    if ((k = e.key) == key ||
-                        (e.hash == hash && key.equals(k))) {
-                        oldValue = e.value;
-                        e.value = value;
-                        ++modCount;
+        addCount(1L, len);
+        return null;
+    }
+
+    /** Implementation for computeIfAbsent */
+    private final V internalComputeIfAbsent(K k, Function<? super K, ? extends V> mf) {
+        if (k == null || mf == null)
+            throw new NullPointerException();
+        int h = spread(k.hashCode());
+        V val = null;
+        int len = 0;
+        for (Node<K,V>[] tab = table;;) {
+            Node<K,V> f; int i; Object fk;
+            if (tab == null)
+                tab = initTable();
+            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
+                Node<K,V> node = new Node<K,V>(h, k, null, null);
+                synchronized (node) {
+                    if (casTabAt(tab, i, null, node)) {
+                        len = 1;
+                        try {
+                            if ((val = mf.apply(k)) != null)
+                                node.val = val;
+                        } finally {
+                            if (val == null)
+                                setTabAt(tab, i, null);
+                        }
+                    }
+                }
+                if (len != 0)
+                    break;
+            }
+            else if (f.hash < 0) {
+                if ((fk = f.key) instanceof TreeBin) {
+                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
+                    long stamp = t.writeLock();
+                    boolean added = false;
+                    try {
+                        if (tabAt(tab, i) == f) {
+                            len = 2;
+                            Class<?> cc = comparableClassFor(k.getClass());
+                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
+                            if (p != null)
+                                val = p.val;
+                            else if ((val = mf.apply(k)) != null) {
+                                added = true;
+                                t.putTreeNode(h, k, val);
+                            }
+                        }
+                    } finally {
+                        t.unlockWrite(stamp);
+                    }
+                    if (len != 0) {
+                        if (!added)
+                            return val;
                         break;
                     }
                 }
-            } finally {
-                unlock();
+                else
+                    tab = (Node<K,V>[])fk;
             }
-            return oldValue;
+            else {
+                boolean added = false;
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        len = 1;
+                        for (Node<K,V> e = f;; ++len) {
+                            Object ek; V ev;
+                            if (e.hash == h &&
+                                ((ek = e.key) == k || k.equals(ek))) {
+                                val = e.val;
+                                break;
+                            }
+                            Node<K,V> last = e;
+                            if ((e = e.next) == null) {
+                                if ((val = mf.apply(k)) != null) {
+                                    added = true;
+                                    last.next = new Node<K,V>(h, k, val, null);
+                                    if (len > TREE_THRESHOLD)
+                                        replaceWithTreeBin(tab, i, k);
+                                }
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (len != 0) {
+                    if (!added)
+                        return val;
+                    break;
+                }
+            }
         }
-
-        final void clear() {
-            lock();
-            try {
-                HashEntry<K,V>[] tab = table;
-                for (int i = 0; i < tab.length ; i++)
-                    setEntryAt(tab, i, null);
-                ++modCount;
-                count = 0;
-            } finally {
-                unlock();
+        if (val != null)
+            addCount(1L, len);
+        return val;
+    }
+
+    /** Implementation for compute */
+    private final V internalCompute(K k, boolean onlyIfPresent,
+                                    BiFunction<? super K, ? super V, ? extends V> mf) {
+        if (k == null || mf == null)
+            throw new NullPointerException();
+        int h = spread(k.hashCode());
+        V val = null;
+        int delta = 0;
+        int len = 0;
+        for (Node<K,V>[] tab = table;;) {
+            Node<K,V> f; int i, fh; Object fk;
+            if (tab == null)
+                tab = initTable();
+            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
+                if (onlyIfPresent)
+                    break;
+                Node<K,V> node = new Node<K,V>(h, k, null, null);
+                synchronized (node) {
+                    if (casTabAt(tab, i, null, node)) {
+                        try {
+                            len = 1;
+                            if ((val = mf.apply(k, null)) != null) {
+                                node.val = val;
+                                delta = 1;
+                            }
+                        } finally {
+                            if (delta == 0)
+                                setTabAt(tab, i, null);
+                        }
+                    }
+                }
+                if (len != 0)
+                    break;
+            }
+            else if ((fh = f.hash) < 0) {
+                if ((fk = f.key) instanceof TreeBin) {
+                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
+                    long stamp = t.writeLock();
+                    try {
+                        if (tabAt(tab, i) == f) {
+                            len = 2;
+                            Class<?> cc = comparableClassFor(k.getClass());
+                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
+                            if (p != null || !onlyIfPresent) {
+                                V pv = (p == null) ? null : p.val;
+                                if ((val = mf.apply(k, pv)) != null) {
+                                    if (p != null)
+                                        p.val = val;
+                                    else {
+                                        delta = 1;
+                                        t.putTreeNode(h, k, val);
+                                    }
+                                }
+                                else if (p != null) {
+                                    delta = -1;
+                                    t.deleteTreeNode(p);
+                                }
+                            }
+                        }
+                    } finally {
+                        t.unlockWrite(stamp);
+                    }
+                    if (len != 0)
+                        break;
+                }
+                else
+                    tab = (Node<K,V>[])fk;
+            }
+            else {
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        len = 1;
+                        for (Node<K,V> e = f, pred = null;; ++len) {
+                            Object ek;
+                            if (e.hash == h &&
+                                ((ek = e.key) == k || k.equals(ek))) {
+                                val = mf.apply(k, e.val);
+                                if (val != null)
+                                    e.val = val;
+                                else {
+                                    delta = -1;
+                                    Node<K,V> en = e.next;
+                                    if (pred != null)
+                                        pred.next = en;
+                                    else
+                                        setTabAt(tab, i, en);
+                                }
+                                break;
+                            }
+                            pred = e;
+                            if ((e = e.next) == null) {
+                                if (!onlyIfPresent &&
+                                    (val = mf.apply(k, null)) != null) {
+                                    pred.next = new Node<K,V>(h, k, val, null);
+                                    delta = 1;
+                                    if (len > TREE_THRESHOLD)
+                                        replaceWithTreeBin(tab, i, k);
+                                }
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (len != 0)
+                    break;
+            }
+        }
+        if (delta != 0)
+            addCount((long)delta, len);
+        return val;
+    }
+
+    /** Implementation for merge */
+    private final V internalMerge(K k, V v,
+                                  BiFunction<? super V, ? super V, ? extends V> mf) {
+        if (k == null || v == null || mf == null)
+            throw new NullPointerException();
+        int h = spread(k.hashCode());
+        V val = null;
+        int delta = 0;
+        int len = 0;
+        for (Node<K,V>[] tab = table;;) {
+            int i; Node<K,V> f; Object fk;
+            if (tab == null)
+                tab = initTable();
+            else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) {
+                if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null))) {
+                    delta = 1;
+                    val = v;
+                    break;
+                }
+            }
+            else if (f.hash < 0) {
+                if ((fk = f.key) instanceof TreeBin) {
+                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
+                    long stamp = t.writeLock();
+                    try {
+                        if (tabAt(tab, i) == f) {
+                            len = 2;
+                            Class<?> cc = comparableClassFor(k.getClass());
+                            TreeNode<K,V> p = t.getTreeNode(h, k, t.root, cc);
+                            val = (p == null) ? v : mf.apply(p.val, v);
+                            if (val != null) {
+                                if (p != null)
+                                    p.val = val;
+                                else {
+                                    delta = 1;
+                                    t.putTreeNode(h, k, val);
+                                }
+                            }
+                            else if (p != null) {
+                                delta = -1;
+                                t.deleteTreeNode(p);
+                            }
+                        }
+                    } finally {
+                        t.unlockWrite(stamp);
+                    }
+                    if (len != 0)
+                        break;
+                }
+                else
+                    tab = (Node<K,V>[])fk;
+            }
+            else {
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        len = 1;
+                        for (Node<K,V> e = f, pred = null;; ++len) {
+                            Object ek;
+                            if (e.hash == h &&
+                                ((ek = e.key) == k || k.equals(ek))) {
+                                val = mf.apply(e.val, v);
+                                if (val != null)
+                                    e.val = val;
+                                else {
+                                    delta = -1;
+                                    Node<K,V> 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 = v;
+                                pred.next = new Node<K,V>(h, k, val, null);
+                                if (len > TREE_THRESHOLD)
+                                    replaceWithTreeBin(tab, i, k);
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (len != 0)
+                    break;
+            }
+        }
+        if (delta != 0)
+            addCount((long)delta, len);
+        return val;
+    }
+
+    /** Implementation for putAll */
+    private final void internalPutAll(Map<? extends K, ? extends V> m) {
+        tryPresize(m.size());
+        long delta = 0L;     // number of uncommitted additions
+        boolean npe = false; // to throw exception on exit for nulls
+        try {                // to clean up counts on other exceptions
+            for (Map.Entry<?, ? extends V> entry : m.entrySet()) {
+                Object k; V v;
+                if (entry == null || (k = entry.getKey()) == null ||
+                    (v = entry.getValue()) == null) {
+                    npe = true;
+                    break;
+                }
+                int h = spread(k.hashCode());
+                for (Node<K,V>[] tab = table;;) {
+                    int i; Node<K,V> f; int fh; Object fk;
+                    if (tab == null)
+                        tab = initTable();
+                    else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null){
+                        if (casTabAt(tab, i, null, new Node<K,V>(h, k, v, null))) {
+                            ++delta;
+                            break;
+                        }
+                    }
+                    else if ((fh = f.hash) < 0) {
+                        if ((fk = f.key) instanceof TreeBin) {
+                            TreeBin<K,V> t = (TreeBin<K,V>)fk;
+                            long stamp = t.writeLock();
+                            boolean validated = false;
+                            try {
+                                if (tabAt(tab, i) == f) {
+                                    validated = true;
+                                    Class<?> cc = comparableClassFor(k.getClass());
+                                    TreeNode<K,V> p = t.getTreeNode(h, k,
+                                                                    t.root, cc);
+                                    if (p != null)
+                                        p.val = v;
+                                    else {
+                                        ++delta;
+                                        t.putTreeNode(h, k, v);
+                                    }
+                                }
+                            } finally {
+                                t.unlockWrite(stamp);
+                            }
+                            if (validated)
+                                break;
+                        }
+                        else
+                            tab = (Node<K,V>[])fk;
+                    }
+                    else {
+                        int len = 0;
+                        synchronized (f) {
+                            if (tabAt(tab, i) == f) {
+                                len = 1;
+                                for (Node<K,V> e = f;; ++len) {
+                                    Object ek;
+                                    if (e.hash == h &&
+                                        ((ek = e.key) == k || k.equals(ek))) {
+                                        e.val = v;
+                                        break;
+                                    }
+                                    Node<K,V> last = e;
+                                    if ((e = e.next) == null) {
+                                        ++delta;
+                                        last.next = new Node<K,V>(h, k, v, null);
+                                        if (len > TREE_THRESHOLD)
+                                            replaceWithTreeBin(tab, i, k);
+                                        break;
+                                    }
+                                }
+                            }
+                        }
+                        if (len != 0) {
+                            if (len > 1) {
+                                addCount(delta, len);
+                                delta = 0L;
+                            }
+                            break;
+                        }
+                    }
+                }
+            }
+        } finally {
+            if (delta != 0L)
+                addCount(delta, 2);
+        }
+        if (npe)
+            throw new NullPointerException();
+    }
+
+    /**
+     * Implementation for clear. Steps through each bin, removing all
+     * nodes.
+     */
+    private final void internalClear() {
+        long delta = 0L; // negative number of deletions
+        int i = 0;
+        Node<K,V>[] tab = table;
+        while (tab != null && i < tab.length) {
+            Node<K,V> f = tabAt(tab, i);
+            if (f == null)
+                ++i;
+            else if (f.hash < 0) {
+                Object fk;
+                if ((fk = f.key) instanceof TreeBin) {
+                    TreeBin<K,V> t = (TreeBin<K,V>)fk;
+                    long stamp = t.writeLock();
+                    try {
+                        if (tabAt(tab, i) == f) {
+                            for (Node<K,V> p = t.first; p != null; p = p.next)
+                                --delta;
+                            t.first = null;
+                            t.root = null;
+                            ++i;
+                        }
+                    } finally {
+                        t.unlockWrite(stamp);
+                    }
+                }
+                else
+                    tab = (Node<K,V>[])fk;
+            }
+            else {
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        for (Node<K,V> e = f; e != null; e = e.next)
+                            --delta;
+                        setTabAt(tab, i, null);
+                        ++i;
+                    }
+                }
+            }
+        }
+        if (delta != 0L)
+            addCount(delta, -1);
+    }
+
+    /* ---------------- Table Initialization and Resizing -------------- */
+
+    /**
+     * Returns a power of two table size for the given desired capacity.
+     * See Hackers Delight, sec 3.2
+     */
+    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;
+    }
+
+    /**
+     * Initializes table, using the size recorded in sizeCtl.
+     */
+    private final Node<K,V>[] initTable() {
+        Node<K,V>[] tab; int sc;
+        while ((tab = table) == null) {
+            if ((sc = sizeCtl) < 0)
+                Thread.yield(); // lost initialization race; just spin
+            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
+                try {
+                    if ((tab = table) == null) {
+                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
+                        table = tab = (Node<K,V>[])new Node[n];
+                        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) {
+        Cell[] as; long b, s;
+        if ((as = counterCells) != null ||
+            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
+            Cell 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<K,V>[] tab, nt; int sc;
+            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
+                   tab.length < MAXIMUM_CAPACITY) {
+                if (sc < 0) {
+                    if (sc == -1 || transferIndex <= transferOrigin ||
+                        (nt = nextTable) == null)
+                        break;
+                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc - 1))
+                        transfer(tab, nt);
+                }
+                else if (U.compareAndSwapInt(this, SIZECTL, sc, -2))
+                    transfer(tab, null);
+                s = sumCount();
             }
         }
     }
 
-    // Accessing segments
-
     /**
-     * Gets the jth element of given segment array (if nonnull) with
-     * volatile element access semantics via Unsafe. (The null check
-     * can trigger harmlessly only during deserialization.) Note:
-     * because each element of segments array is set only once (using
-     * fully ordered writes), some performance-sensitive methods rely
-     * on this method only as a recheck upon null reads.
+     * Tries to presize table to accommodate the given number of elements.
+     *
+     * @param size number of elements (doesn't need to be perfectly accurate)
      */
-    @SuppressWarnings("unchecked")
-    static final <K,V> Segment<K,V> segmentAt(Segment<K,V>[] ss, int j) {
-        long u = (j << SSHIFT) + SBASE;
-        return ss == null ? null :
-            (Segment<K,V>) UNSAFE.getObjectVolatile(ss, u);
-    }
-
-    /**
-     * Returns the segment for the given index, creating it and
-     * recording in segment table (via CAS) if not already present.
-     *
-     * @param k the index
-     * @return the segment
-     */
-    @SuppressWarnings("unchecked")
-    private Segment<K,V> ensureSegment(int k) {
-        final Segment<K,V>[] ss = this.segments;
-        long u = (k << SSHIFT) + SBASE; // raw offset
-        Segment<K,V> seg;
-        if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
-            Segment<K,V> proto = ss[0]; // use segment 0 as prototype
-            int cap = proto.table.length;
-            float lf = proto.loadFactor;
-            int threshold = (int)(cap * lf);
-            HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry<?,?>[cap];
-            if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
-                == null) { // recheck
-                Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
-                while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
-                       == null) {
-                    if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
-                        break;
+    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<K,V>[] 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) {
+                            table = (Node<K,V>[])new Node[n];
+                            sc = n - (n >>> 2);
+                        }
+                    } finally {
+                        sizeCtl = sc;
+                    }
                 }
             }
+            else if (c <= sc || n >= MAXIMUM_CAPACITY)
+                break;
+            else if (tab == table &&
+                     U.compareAndSwapInt(this, SIZECTL, sc, -2))
+                transfer(tab, null);
         }
-        return seg;
     }
 
-    // Hash-based segment and entry accesses
-
     /**
-     * Gets the segment for the given hash code.
+     * Moves and/or copies the nodes in each bin to new table. See
+     * above for explanation.
      */
-    @SuppressWarnings("unchecked")
-    private Segment<K,V> segmentForHash(int h) {
-        long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
-        return (Segment<K,V>) UNSAFE.getObjectVolatile(segments, u);
+    private final void transfer(Node<K,V>[] tab, Node<K,V>[] 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 {
+                nextTab = (Node<K,V>[])new Node[n << 1];
+            } catch (Throwable ex) {      // try to cope with OOME
+                sizeCtl = Integer.MAX_VALUE;
+                return;
+            }
+            nextTable = nextTab;
+            transferOrigin = n;
+            transferIndex = n;
+            Node<K,V> rev = new Node<K,V>(MOVED, tab, null, null);
+            for (int k = n; k > 0;) {    // progressively reveal ready slots
+                int nextk = (k > stride) ? k - stride : 0;
+                for (int m = nextk; m < k; ++m)
+                    nextTab[m] = rev;
+                for (int m = n + nextk; m < n + k; ++m)
+                    nextTab[m] = rev;
+                U.putOrderedInt(this, TRANSFERORIGIN, k = nextk);
+            }
+        }
+        int nextn = nextTab.length;
+        Node<K,V> fwd = new Node<K,V>(MOVED, nextTab, null, null);
+        boolean advance = true;
+        for (int i = 0, bound = 0;;) {
+            int nextIndex, nextBound; Node<K,V> f; Object fk;
+            while (advance) {
+                if (--i >= bound)
+                    advance = false;
+                else if ((nextIndex = transferIndex) <= transferOrigin) {
+                    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) {
+                for (int sc;;) {
+                    if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) {
+                        if (sc == -1) {
+                            nextTable = null;
+                            table = nextTab;
+                            sizeCtl = (n << 1) - (n >>> 1);
+                        }
+                        return;
+                    }
+                }
+            }
+            else if ((f = tabAt(tab, i)) == null) {
+                if (casTabAt(tab, i, null, fwd)) {
+                    setTabAt(nextTab, i, null);
+                    setTabAt(nextTab, i + n, null);
+                    advance = true;
+                }
+            }
+            else if (f.hash >= 0) {
+                synchronized (f) {
+                    if (tabAt(tab, i) == f) {
+                        int runBit = f.hash & n;
+                        Node<K,V> lastRun = f, lo = null, hi = null;
+                        for (Node<K,V> p = f.next; p != null; p = p.next) {
+                            int b = p.hash & n;
+                            if (b != runBit) {
+                                runBit = b;
+                                lastRun = p;
+                            }
+                        }
+                        if (runBit == 0)
+                            lo = lastRun;
+                        else
+                            hi = lastRun;
+                        for (Node<K,V> p = f; p != lastRun; p = p.next) {
+                            int ph = p.hash; Object pk = p.key; V pv = p.val;
+                            if ((ph & n) == 0)
+                                lo = new Node<K,V>(ph, pk, pv, lo);
+                            else
+                                hi = new Node<K,V>(ph, pk, pv, hi);
+                        }
+                        setTabAt(nextTab, i, lo);
+                        setTabAt(nextTab, i + n, hi);
+                        setTabAt(tab, i, fwd);
+                        advance = true;
+                    }
+                }
+            }
+            else if ((fk = f.key) instanceof TreeBin) {
+                TreeBin<K,V> t = (TreeBin<K,V>)fk;
+                long stamp = t.writeLock();
+                try {
+                    if (tabAt(tab, i) == f) {
+                        TreeNode<K,V> root;
+                        Node<K,V> ln = null, hn = null;
+                        if ((root = t.root) != null) {
+                            Node<K,V> e, p; TreeNode<K,V> lr, rr; int lh;
+                            TreeBin<K,V> lt = null, ht = null;
+                            for (lr = root; lr.left != null; lr = lr.left);
+                            for (rr = root; rr.right != null; rr = rr.right);
+                            if ((lh = lr.hash) == rr.hash) { // move entire tree
+                                if ((lh & n) == 0)
+                                    lt = t;
+                                else
+                                    ht = t;
+                            }
+                            else {
+                                lt = new TreeBin<K,V>();
+                                ht = new TreeBin<K,V>();
+                                int lc = 0, hc = 0;
+                                for (e = t.first; e != null; e = e.next) {
+                                    int h = e.hash;
+                                    Object k = e.key; V v = e.val;
+                                    if ((h & n) == 0) {
+                                        ++lc;
+                                        lt.putTreeNode(h, k, v);
+                                    }
+                                    else {
+                                        ++hc;
+                                        ht.putTreeNode(h, k, v);
+                                    }
+                                }
+                                if (lc < TREE_THRESHOLD) { // throw away
+                                    for (p = lt.first; p != null; p = p.next)
+                                        ln = new Node<K,V>(p.hash, p.key,
+                                                           p.val, ln);
+                                    lt = null;
+                                }
+                                if (hc < TREE_THRESHOLD) {
+                                    for (p = ht.first; p != null; p = p.next)
+                                        hn = new Node<K,V>(p.hash, p.key,
+                                                           p.val, hn);
+                                    ht = null;
+                                }
+                            }
+                            if (ln == null && lt != null)
+                                ln = new Node<K,V>(MOVED, lt, null, null);
+                            if (hn == null && ht != null)
+                                hn = new Node<K,V>(MOVED, ht, null, null);
+                        }
+                        setTabAt(nextTab, i, ln);
+                        setTabAt(nextTab, i + n, hn);
+                        setTabAt(tab, i, fwd);
+                        advance = true;
+                    }
+                } finally {
+                    t.unlockWrite(stamp);
+                }
+            }
+            else
+                advance = true; // already processed
+        }
     }
 
+    /* ---------------- Counter support -------------- */
+
+    final long sumCount() {
+        Cell[] as = counterCells; Cell 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 (;;) {
+            Cell[] as; Cell 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
+                        Cell r = new Cell(x); // Optimistic create
+                        if (cellsBusy == 0 &&
+                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
+                            boolean created = false;
+                            try {               // Recheck under lock
+                                Cell[] 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
+                            Cell[] rs = new Cell[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) {
+                        Cell[] rs = new Cell[2];
+                        rs[h & 1] = new Cell(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
+        }
+    }
+
+    /* ----------------Table Traversal -------------- */
+
     /**
-     * Gets the table entry for the given segment and hash code.
+     * 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.
      */
-    @SuppressWarnings("unchecked")
-    static final <K,V> HashEntry<K,V> entryForHash(Segment<K,V> seg, int h) {
-        HashEntry<K,V>[] tab;
-        return (seg == null || (tab = seg.table) == null) ? null :
-            (HashEntry<K,V>) UNSAFE.getObjectVolatile
-            (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
+    static class Traverser<K,V> {
+        Node<K,V>[] tab;        // current table; updated if resized
+        Node<K,V> next;         // the next entry to use
+        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<K,V>[] 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<K,V> advance() {
+            Node<K,V> e;
+            if ((e = next) != null)
+                e = e.next;
+            for (;;) {
+                Node<K,V>[] t; int i, n; Object ek;  // 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, index)) != null && e.hash < 0) {
+                    if ((ek = e.key) instanceof TreeBin)
+                        e = ((TreeBin<K,V>)ek).first;
+                    else {
+                        tab = (Node<K,V>[])ek;
+                        e = null;
+                        continue;
+                    }
+                }
+                if ((index += baseSize) >= n)
+                    index = ++baseIndex;    // visit upper slots if present
+            }
+        }
     }
 
+    /**
+     * Base of key, value, and entry Iterators. Adds fields to
+     * Traverser to support iterator.remove
+     */
+    static class BaseIterator<K,V> extends Traverser<K,V> {
+        final ConcurrentHashMap<K,V> map;
+        Node<K,V> lastReturned;
+        BaseIterator(Node<K,V>[] tab, int size, int index, int limit,
+                    ConcurrentHashMap<K,V> 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<K,V> p;
+            if ((p = lastReturned) == null)
+                throw new IllegalStateException();
+            lastReturned = null;
+            map.internalReplace((K)p.key, null, null);
+        }
+    }
+
+    static final class KeyIterator<K,V> extends BaseIterator<K,V>
+        implements Iterator<K>, Enumeration<K> {
+        KeyIterator(Node<K,V>[] tab, int index, int size, int limit,
+                    ConcurrentHashMap<K,V> map) {
+            super(tab, index, size, limit, map);
+        }
+
+        public final K next() {
+            Node<K,V> p;
+            if ((p = next) == null)
+                throw new NoSuchElementException();
+            K k = (K)p.key;
+            lastReturned = p;
+            advance();
+            return k;
+        }
+
+        public final K nextElement() { return next(); }
+    }
+
+    static final class ValueIterator<K,V> extends BaseIterator<K,V>
+        implements Iterator<V>, Enumeration<V> {
+        ValueIterator(Node<K,V>[] tab, int index, int size, int limit,
+                      ConcurrentHashMap<K,V> map) {
+            super(tab, index, size, limit, map);
+        }
+
+        public final V next() {
+            Node<K,V> 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<K,V> extends BaseIterator<K,V>
+        implements Iterator<Map.Entry<K,V>> {
+        EntryIterator(Node<K,V>[] tab, int index, int size, int limit,
+                      ConcurrentHashMap<K,V> map) {
+            super(tab, index, size, limit, map);
+        }
+
+        public final Map.Entry<K,V> next() {
+            Node<K,V> p;
+            if ((p = next) == null)
+                throw new NoSuchElementException();
+            K k = (K)p.key;
+            V v = p.val;
+            lastReturned = p;
+            advance();
+            return new MapEntry<K,V>(k, v, map);
+        }
+    }
+
+    static final class KeySpliterator<K,V> extends Traverser<K,V>
+        implements Spliterator<K> {
+        long est;               // size estimate
+        KeySpliterator(Node<K,V>[] tab, int size, int index, int limit,
+                       long est) {
+            super(tab, size, index, limit);
+            this.est = est;
+        }
+
+        public Spliterator<K> trySplit() {
+            int i, f, h;
+            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
+                new KeySpliterator<K,V>(tab, baseSize, baseLimit = h,
+                                        f, est >>>= 1);
+        }
+
+        public void forEachRemaining(Consumer<? super K> action) {
+            if (action == null) throw new NullPointerException();
+            for (Node<K,V> p; (p = advance()) != null;)
+                action.accept((K)p.key);
+        }
+
+        public boolean tryAdvance(Consumer<? super K> action) {
+            if (action == null) throw new NullPointerException();
+            Node<K,V> p;
+            if ((p = advance()) == null)
+                return false;
+            action.accept((K)p.key);
+            return true;
+        }
+
+        public long estimateSize() { return est; }
+
+        public int characteristics() {
+            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
+                Spliterator.NONNULL;
+        }
+    }
+
+    static final class ValueSpliterator<K,V> extends Traverser<K,V>
+        implements Spliterator<V> {
+        long est;               // size estimate
+        ValueSpliterator(Node<K,V>[] tab, int size, int index, int limit,
+                         long est) {
+            super(tab, size, index, limit);
+            this.est = est;
+        }
+
+        public Spliterator<V> trySplit() {
+            int i, f, h;
+            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
+                new ValueSpliterator<K,V>(tab, baseSize, baseLimit = h,
+                                          f, est >>>= 1);
+        }
+
+        public void forEachRemaining(Consumer<? super V> action) {
+            if (action == null) throw new NullPointerException();
+            for (Node<K,V> p; (p = advance()) != null;)
+                action.accept(p.val);
+        }
+
+        public boolean tryAdvance(Consumer<? super V> action) {
+            if (action == null) throw new NullPointerException();
+            Node<K,V> 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<K,V> extends Traverser<K,V>
+        implements Spliterator<Map.Entry<K,V>> {
+        final ConcurrentHashMap<K,V> map; // To export MapEntry
+        long est;               // size estimate
+        EntrySpliterator(Node<K,V>[] tab, int size, int index, int limit,
+                         long est, ConcurrentHashMap<K,V> map) {
+            super(tab, size, index, limit);
+            this.map = map;
+            this.est = est;
+        }
+
+        public Spliterator<Map.Entry<K,V>> trySplit() {
+            int i, f, h;
+            return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null :
+                new EntrySpliterator<K,V>(tab, baseSize, baseLimit = h,
+                                          f, est >>>= 1, map);
+        }
+
+        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
+            if (action == null) throw new NullPointerException();
+            for (Node<K,V> p; (p = advance()) != null; )
+                action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
+        }
+
+        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
+            if (action == null) throw new NullPointerException();
+            Node<K,V> p;
+            if ((p = advance()) == null)
+                return false;
+            action.accept(new MapEntry<K,V>((K)p.key, p.val, map));
+            return true;
+        }
+
+        public long estimateSize() { return est; }
+
+        public int characteristics() {
+            return Spliterator.DISTINCT | Spliterator.CONCURRENT |
+                Spliterator.NONNULL;
+        }
+    }
+
+
     /* ---------------- Public operations -------------- */
 
     /**
-     * Creates a new, empty map with the specified initial
-     * capacity, load factor and concurrency level.
-     *
-     * @param initialCapacity the initial capacity. The implementation
-     * performs internal sizing to accommodate this many elements.
-     * @param loadFactor  the load factor threshold, used to control resizing.
-     * Resizing may be performed when the average number of elements per
-     * bin exceeds this threshold.
-     * @param concurrencyLevel the estimated number of concurrently
-     * updating threads. The implementation performs internal sizing
-     * to try to accommodate this many threads.
-     * @throws IllegalArgumentException if the initial capacity is
-     * negative or the load factor or concurrencyLevel are
-     * nonpositive.
+     * Creates a new, empty map with the default initial table size (16).
      */
-    @SuppressWarnings("unchecked")
-    public ConcurrentHashMap(int initialCapacity,
-                             float loadFactor, int concurrencyLevel) {
-        if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
-            throw new IllegalArgumentException();
-        if (concurrencyLevel > MAX_SEGMENTS)
-            concurrencyLevel = MAX_SEGMENTS;
-        // Find power-of-two sizes best matching arguments
-        int sshift = 0;
-        int ssize = 1;
-        while (ssize < concurrencyLevel) {
-            ++sshift;
-            ssize <<= 1;
-        }
-        this.segmentShift = 32 - sshift;
-        this.segmentMask = ssize - 1;
-        if (initialCapacity > MAXIMUM_CAPACITY)
-            initialCapacity = MAXIMUM_CAPACITY;
-        int c = initialCapacity / ssize;
-        if (c * ssize < initialCapacity)
-            ++c;
-        int cap = MIN_SEGMENT_TABLE_CAPACITY;
-        while (cap < c)
-            cap <<= 1;
-        // create segments and segments[0]
-        Segment<K,V> s0 =
-            new Segment<K,V>(loadFactor, (int)(cap * loadFactor),
-                             (HashEntry<K,V>[])new HashEntry<?,?>[cap]);
-        Segment<K,V>[] ss = (Segment<K,V>[])new Segment<?,?>[ssize];
-        UNSAFE.putOrderedObject(ss, SBASE, s0); // ordered write of segments[0]
-        this.segments = ss;
+    public ConcurrentHashMap() {
     }
 
     /**
-     * Creates a new, empty map with the specified initial capacity
-     * and load factor and with the default concurrencyLevel (16).
+     * Creates a new, empty map with an initial table size
+     * accommodating the specified number of elements without the need
+     * to dynamically resize.
      *
      * @param initialCapacity The implementation performs internal
      * sizing to accommodate this many elements.
-     * @param loadFactor  the load factor threshold, used to control resizing.
-     * Resizing may be performed when the average number of elements per
-     * bin exceeds this threshold.
+     * @throws IllegalArgumentException if the initial capacity of
+     * elements is negative
+     */
+    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;
+    }
+
+    /**
+     * Creates a new map with the same mappings as the given map.
+     *
+     * @param m the map
+     */
+    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
+        this.sizeCtl = DEFAULT_CAPACITY;
+        internalPutAll(m);
+    }
+
+    /**
+     * Creates a new, empty map with an initial table size based on
+     * the given number of elements ({@code initialCapacity}) and
+     * initial table density ({@code loadFactor}).
+     *
+     * @param initialCapacity the initial capacity. The implementation
+     * performs internal sizing to accommodate this many elements,
+     * given the specified load factor.
+     * @param loadFactor the load factor (table density) for
+     * establishing the initial table size
      * @throws IllegalArgumentException if the initial capacity of
      * elements is negative or the load factor is nonpositive
      *
      * @since 1.6
      */
     public ConcurrentHashMap(int initialCapacity, float loadFactor) {
-        this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL);
+        this(initialCapacity, loadFactor, 1);
     }
 
     /**
-     * Creates a new, empty map with the specified initial capacity,
-     * and with default load factor (0.75) and concurrencyLevel (16).
+     * Creates a new, empty map with an initial table size based on
+     * the given number of elements ({@code initialCapacity}), table
+     * density ({@code loadFactor}), and number of concurrently
+     * updating threads ({@code concurrencyLevel}).
      *
      * @param initialCapacity the initial capacity. The implementation
-     * performs internal sizing to accommodate this many elements.
+     * performs internal sizing to accommodate this many elements,
+     * given the specified load factor.
+     * @param loadFactor the load factor (table density) for
+     * establishing the initial table size
+     * @param concurrencyLevel the estimated number of concurrently
+     * updating threads. The implementation may use this value as
+     * a sizing hint.
+     * @throws IllegalArgumentException if the initial capacity is
+     * negative or the load factor or concurrencyLevel are
+     * nonpositive
+     */
+    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;
+    }
+
+    /**
+     * Creates a new {@link Set} backed by a ConcurrentHashMap
+     * from the given type to {@code Boolean.TRUE}.
+     *
+     * @return the new set
+     * @since 1.8
+     */
+    public static <K> KeySetView<K,Boolean> newKeySet() {
+        return new KeySetView<K,Boolean>
+            (new ConcurrentHashMap<K,Boolean>(), Boolean.TRUE);
+    }
+
+    /**
+     * Creates a new {@link Set} backed by a ConcurrentHashMap
+     * from the given type to {@code Boolean.TRUE}.
+     *
+     * @param initialCapacity The implementation performs internal
+     * sizing to accommodate this many elements.
      * @throws IllegalArgumentException if the initial capacity of
-     * elements is negative.
+     * elements is negative
+     * @return the new set
+     * @since 1.8
      */
-    public ConcurrentHashMap(int initialCapacity) {
-        this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
-    }
-
-    /**
-     * Creates a new, empty map with a default initial capacity (16),
-     * load factor (0.75) and concurrencyLevel (16).
-     */
-    public ConcurrentHashMap() {
-        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
-    }
-
-    /**
-     * Creates a new map with the same mappings as the given map.
-     * The map is created with a capacity of 1.5 times the number
-     * of mappings in the given map or 16 (whichever is greater),
-     * and a default load factor (0.75) and concurrencyLevel (16).
-     *
-     * @param m the map
-     */
-    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
-        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
-                      DEFAULT_INITIAL_CAPACITY),
-             DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL);
-        putAll(m);
+    public static <K> KeySetView<K,Boolean> newKeySet(int initialCapacity) {
+        return new KeySetView<K,Boolean>
+            (new ConcurrentHashMap<K,Boolean>(initialCapacity), Boolean.TRUE);
     }
 
     /**
@@ -834,38 +2639,7 @@
      * @return {@code true} if this map contains no key-value mappings
      */
     public boolean isEmpty() {
-        /*
-         * Sum per-segment modCounts to avoid mis-reporting when
-         * elements are concurrently added and removed in one segment
-         * while checking another, in which case the table was never
-         * actually empty at any point. (The sum ensures accuracy up
-         * through at least 1<<31 per-segment modifications before
-         * recheck.)  Methods size() and containsValue() use similar
-         * constructions for stability checks.
-         */
-        long sum = 0L;
-        final Segment<K,V>[] segments = this.segments;
-        for (int j = 0; j < segments.length; ++j) {
-            Segment<K,V> seg = segmentAt(segments, j);
-            if (seg != null) {
-                if (seg.count != 0)
-                    return false;
-                sum += seg.modCount;
-            }
-        }
-        if (sum != 0L) { // recheck unless no modifications
-            for (int j = 0; j < segments.length; ++j) {
-                Segment<K,V> seg = segmentAt(segments, j);
-                if (seg != null) {
-                    if (seg.count != 0)
-                        return false;
-                    sum -= seg.modCount;
-                }
-            }
-            if (sum != 0L)
-                return false;
-        }
-        return true;
+        return sumCount() <= 0L; // ignore transient negative values
     }
 
     /**
@@ -876,43 +2650,25 @@
      * @return the number of key-value mappings in this map
      */
     public int size() {
-        // Try a few times to get accurate count. On failure due to
-        // continuous async changes in table, resort to locking.
-        final Segment<K,V>[] segments = this.segments;
-        int size;
-        boolean overflow; // true if size overflows 32 bits
-        long sum;         // sum of modCounts
-        long last = 0L;   // previous sum
-        int retries = -1; // first iteration isn't retry
-        try {
-            for (;;) {
-                if (retries++ == RETRIES_BEFORE_LOCK) {
-                    for (int j = 0; j < segments.length; ++j)
-                        ensureSegment(j).lock(); // force creation
-                }
-                sum = 0L;
-                size = 0;
-                overflow = false;
-                for (int j = 0; j < segments.length; ++j) {
-                    Segment<K,V> seg = segmentAt(segments, j);
-                    if (seg != null) {
-                        sum += seg.modCount;
-                        int c = seg.count;
-                        if (c < 0 || (size += c) < 0)
-                            overflow = true;
-                    }
-                }
-                if (sum == last)
-                    break;
-                last = sum;
-            }
-        } finally {
-            if (retries > RETRIES_BEFORE_LOCK) {
-                for (int j = 0; j < segments.length; ++j)
-                    segmentAt(segments, j).unlock();
-            }
-        }
-        return overflow ? Integer.MAX_VALUE : size;
+        long n = sumCount();
+        return ((n < 0L) ? 0 :
+                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
+                (int)n);
+    }
+
+    /**
+     * Returns the number of mappings. This method should be used
+     * instead of {@link #size} because a ConcurrentHashMap may
+     * contain more mappings than can be represented as an int. The
+     * value returned is an estimate; the actual count may differ if
+     * there are concurrent insertions or removals.
+     *
+     * @return the number of mappings
+     * @since 1.8
+     */
+    public long mappingCount() {
+        long n = sumCount();
+        return (n < 0L) ? 0L : n; // ignore transient negative values
     }
 
     /**
@@ -926,23 +2682,24 @@
      *
      * @throws NullPointerException if the specified key is null
      */
-    @SuppressWarnings("unchecked")
     public V get(Object key) {
-        Segment<K,V> s; // manually integrate access methods to reduce overhead
-        HashEntry<K,V>[] tab;
-        int h = hash(key);
-        long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
-        if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
-            (tab = s.table) != null) {
-            for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
-                     (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
-                 e != null; e = e.next) {
-                K k;
-                if ((k = e.key) == key || (e.hash == h && key.equals(k)))
-                    return e.value;
-            }
-        }
-        return null;
+        return internalGet(key);
+    }
+
+    /**
+     * Returns the value to which the specified key is mapped, or the
+     * given default value if this map contains no mapping for the
+     * key.
+     *
+     * @param key the key whose associated value is to be returned
+     * @param defaultValue the value to return if this map contains
+     * no mapping for the given key
+     * @return the mapping for the key, if present; else the default value
+     * @throws NullPointerException if the specified key is null
+     */
+    public V getOrDefault(Object key, V defaultValue) {
+        V v;
+        return (v = internalGet(key)) == null ? defaultValue : v;
     }
 
     /**
@@ -954,29 +2711,14 @@
      *         {@code equals} method; {@code false} otherwise
      * @throws NullPointerException if the specified key is null
      */
-    @SuppressWarnings("unchecked")
     public boolean containsKey(Object key) {
-        Segment<K,V> s; // same as get() except no need for volatile value read
-        HashEntry<K,V>[] tab;
-        int h = hash(key);
-        long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
-        if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
-            (tab = s.table) != null) {
-            for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
-                     (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
-                 e != null; e = e.next) {
-                K k;
-                if ((k = e.key) == key || (e.hash == h && key.equals(k)))
-                    return true;
-            }
-        }
-        return false;
+        return internalGet(key) != null;
     }
 
     /**
      * Returns {@code true} if this map maps one or more keys to the
-     * specified value. Note: This method requires a full traversal
-     * of the map, and so is much slower than method {@code containsKey}.
+     * specified value. Note: This method may require a full traversal
+     * of the map, and is much slower than method {@code containsKey}.
      *
      * @param value value whose presence in this map is to be tested
      * @return {@code true} if this map maps one or more keys to the
@@ -984,49 +2726,18 @@
      * @throws NullPointerException if the specified value is null
      */
     public boolean containsValue(Object value) {
-        // Same idea as size()
         if (value == null)
             throw new NullPointerException();
-        final Segment<K,V>[] segments = this.segments;
-        boolean found = false;
-        long last = 0;
-        int retries = -1;
-        try {
-            outer: for (;;) {
-                if (retries++ == RETRIES_BEFORE_LOCK) {
-                    for (int j = 0; j < segments.length; ++j)
-                        ensureSegment(j).lock(); // force creation
-                }
-                long hashSum = 0L;
-                int sum = 0;
-                for (int j = 0; j < segments.length; ++j) {
-                    HashEntry<K,V>[] tab;
-                    Segment<K,V> seg = segmentAt(segments, j);
-                    if (seg != null && (tab = seg.table) != null) {
-                        for (int i = 0 ; i < tab.length; i++) {
-                            HashEntry<K,V> e;
-                            for (e = entryAt(tab, i); e != null; e = e.next) {
-                                V v = e.value;
-                                if (v != null && value.equals(v)) {
-                                    found = true;
-                                    break outer;
-                                }
-                            }
-                        }
-                        sum += seg.modCount;
-                    }
-                }
-                if (retries > 0 && sum == last)
-                    break;
-                last = sum;
-            }
-        } finally {
-            if (retries > RETRIES_BEFORE_LOCK) {
-                for (int j = 0; j < segments.length; ++j)
-                    segmentAt(segments, j).unlock();
+        Node<K,V>[] t;
+        if ((t = table) != null) {
+            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+            for (Node<K,V> p; (p = it.advance()) != null; ) {
+                V v;
+                if ((v = p.val) == value || value.equals(v))
+                    return true;
             }
         }
-        return found;
+        return false;
     }
 
     /**
@@ -1061,17 +2772,8 @@
      *         {@code null} if there was no mapping for {@code key}
      * @throws NullPointerException if the specified key or value is null
      */
-    @SuppressWarnings("unchecked")
     public V put(K key, V value) {
-        Segment<K,V> s;
-        if (value == null)
-            throw new NullPointerException();
-        int hash = hash(key);
-        int j = (hash >>> segmentShift) & segmentMask;
-        if ((s = (Segment<K,V>)UNSAFE.getObject          // nonvolatile; recheck
-             (segments, (j << SSHIFT) + SBASE)) == null) //  in ensureSegment
-            s = ensureSegment(j);
-        return s.put(key, hash, value, false);
+        return internalPut(key, value, false);
     }
 
     /**
@@ -1081,17 +2783,8 @@
      *         or {@code null} if there was no mapping for the key
      * @throws NullPointerException if the specified key or value is null
      */
-    @SuppressWarnings("unchecked")
     public V putIfAbsent(K key, V value) {
-        Segment<K,V> s;
-        if (value == null)
-            throw new NullPointerException();
-        int hash = hash(key);
-        int j = (hash >>> segmentShift) & segmentMask;
-        if ((s = (Segment<K,V>)UNSAFE.getObject
-             (segments, (j << SSHIFT) + SBASE)) == null)
-            s = ensureSegment(j);
-        return s.put(key, hash, value, true);
+        return internalPut(key, value, true);
     }
 
     /**
@@ -1102,8 +2795,105 @@
      * @param m mappings to be stored in this map
      */
     public void putAll(Map<? extends K, ? extends V> m) {
-        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
-            put(e.getKey(), e.getValue());
+        internalPutAll(m);
+    }
+
+    /**
+     * If the specified key is not already associated with a value,
+     * attempts to compute its value using the given mapping function
+     * and enters it into this map unless {@code null}.  The entire
+     * method invocation is performed atomically, so the function is
+     * applied at most once per key.  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 mappingFunction the function to compute a value
+     * @return the current (existing or computed) value associated with
+     *         the specified key, or null if the computed value is null
+     * @throws NullPointerException if the specified key or mappingFunction
+     *         is null
+     * @throws IllegalStateException if the computation detectably
+     *         attempts a recursive update to this map that would
+     *         otherwise never complete
+     * @throws RuntimeException or Error if the mappingFunction does so,
+     *         in which case the mapping is left unestablished
+     */
+    public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
+        return internalComputeIfAbsent(key, mappingFunction);
+    }
+
+    /**
+     * If the value for the specified key is present, attempts to
+     * compute a new mapping given the key and its current mapped
+     * value.  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 a value may be associated
+     * @param remappingFunction the function to compute a value
+     * @return the new value associated with the specified key, or null if none
+     * @throws NullPointerException if the specified key or remappingFunction
+     *         is null
+     * @throws IllegalStateException if the computation detectably
+     *         attempts a recursive update to this map that would
+     *         otherwise never complete
+     * @throws RuntimeException or Error if the remappingFunction does so,
+     *         in which case the mapping is unchanged
+     */
+    public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
+        return internalCompute(key, true, remappingFunction);
+    }
+
+    /**
+     * Attempts to compute a mapping for the specified key and its
+     * current mapped value (or {@code null} if there is no current
+     * mapping). 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 remappingFunction the function to compute a value
+     * @return the new value associated with the specified key, or null if none
+     * @throws NullPointerException if the specified key or remappingFunction
+     *         is null
+     * @throws IllegalStateException if the computation detectably
+     *         attempts a recursive update to this map that would
+     *         otherwise never complete
+     * @throws RuntimeException or Error if the remappingFunction does so,
+     *         in which case the mapping is unchanged
+     */
+    public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
+        return internalCompute(key, false, remappingFunction);
+    }
+
+    /**
+     * 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<? super V, ? super V, ? extends V> remappingFunction) {
+        return internalMerge(key, value, remappingFunction);
     }
 
     /**
@@ -1116,9 +2906,7 @@
      * @throws NullPointerException if the specified key is null
      */
     public V remove(Object key) {
-        int hash = hash(key);
-        Segment<K,V> s = segmentForHash(hash);
-        return s == null ? null : s.remove(key, hash, null);
+        return internalReplace(key, null, null);
     }
 
     /**
@@ -1127,10 +2915,9 @@
      * @throws NullPointerException if the specified key is null
      */
     public boolean remove(Object key, Object value) {
-        int hash = hash(key);
-        Segment<K,V> s;
-        return value != null && (s = segmentForHash(hash)) != null &&
-            s.remove(key, hash, value) != null;
+        if (key == null)
+            throw new NullPointerException();
+        return value != null && internalReplace(key, null, value) != null;
     }
 
     /**
@@ -1139,11 +2926,9 @@
      * @throws NullPointerException if any of the arguments are null
      */
     public boolean replace(K key, V oldValue, V newValue) {
-        int hash = hash(key);
-        if (oldValue == null || newValue == null)
+        if (key == null || oldValue == null || newValue == null)
             throw new NullPointerException();
-        Segment<K,V> s = segmentForHash(hash);
-        return s != null && s.replace(key, hash, oldValue, newValue);
+        return internalReplace(key, newValue, oldValue) != null;
     }
 
     /**
@@ -1154,23 +2939,16 @@
      * @throws NullPointerException if the specified key or value is null
      */
     public V replace(K key, V value) {
-        int hash = hash(key);
-        if (value == null)
+        if (key == null || value == null)
             throw new NullPointerException();
-        Segment<K,V> s = segmentForHash(hash);
-        return s == null ? null : s.replace(key, hash, value);
+        return internalReplace(key, value, null);
     }
 
     /**
      * Removes all of the mappings from this map.
      */
     public void clear() {
-        final Segment<K,V>[] segments = this.segments;
-        for (int j = 0; j < segments.length; ++j) {
-            Segment<K,V> s = segmentAt(segments, j);
-            if (s != null)
-                s.clear();
-        }
+        internalClear();
     }
 
     /**
@@ -1188,10 +2966,29 @@
      * and guarantees to traverse elements as they existed upon
      * construction of the iterator, and may (but is not guaranteed to)
      * reflect any modifications subsequent to construction.
+     *
+     * @return the set view
      */
-    public Set<K> keySet() {
-        Set<K> ks = keySet;
-        return (ks != null) ? ks : (keySet = new KeySet());
+    public KeySetView<K,V> keySet() {
+        KeySetView<K,V> ks = keySet;
+        return (ks != null) ? ks : (keySet = new KeySetView<K,V>(this, null));
+    }
+
+    /**
+     * Returns a {@link Set} view of the keys in this map, using the
+     * given common mapped value for any additions (i.e., {@link
+     * Collection#add} and {@link Collection#addAll(Collection)}).
+     * This is of course only appropriate if it is acceptable to use
+     * the same value for all additions from this view.
+     *
+     * @param mappedValue the mapped value to use for any additions
+     * @return the set view
+     * @throws NullPointerException if the mappedValue is null
+     */
+    public KeySetView<K,V> keySet(V mappedValue) {
+        if (mappedValue == null)
+            throw new NullPointerException();
+        return new KeySetView<K,V>(this, mappedValue);
     }
 
     /**
@@ -1209,10 +3006,12 @@
      * and guarantees to traverse elements as they existed upon
      * construction of the iterator, and may (but is not guaranteed to)
      * reflect any modifications subsequent to construction.
+     *
+     * @return the collection view
      */
     public Collection<V> values() {
-        Collection<V> vs = values;
-        return (vs != null) ? vs : (values = new Values());
+        ValuesView<K,V> vs = values;
+        return (vs != null) ? vs : (values = new ValuesView<K,V>(this));
     }
 
     /**
@@ -1222,18 +3021,19 @@
      * removal, which removes the corresponding mapping from the map,
      * via the {@code Iterator.remove}, {@code Set.remove},
      * {@code removeAll}, {@code retainAll}, and {@code clear}
-     * operations.  It does not support the {@code add} or
-     * {@code addAll} operations.
+     * operations.
      *
      * <p>The view's {@code iterator} is a "weakly consistent" iterator
      * that will never throw {@link ConcurrentModificationException},
      * and guarantees to traverse elements as they existed upon
      * construction of the iterator, and may (but is not guaranteed to)
      * reflect any modifications subsequent to construction.
+     *
+     * @return the set view
      */
     public Set<Map.Entry<K,V>> entrySet() {
-        Set<Map.Entry<K,V>> es = entrySet;
-        return (es != null) ? es : (entrySet = new EntrySet());
+        EntrySetView<K,V> es = entrySet;
+        return (es != null) ? es : (entrySet = new EntrySetView<K,V>(this));
     }
 
     /**
@@ -1243,7 +3043,9 @@
      * @see #keySet()
      */
     public Enumeration<K> keys() {
-        return new KeyIterator();
+        Node<K,V>[] t;
+        int f = (t = table) == null ? 0 : t.length;
+        return new KeyIterator<K,V>(t, f, 0, f, this);
     }
 
     /**
@@ -1253,191 +3055,110 @@
      * @see #values()
      */
     public Enumeration<V> elements() {
-        return new ValueIterator();
+        Node<K,V>[] t;
+        int f = (t = table) == null ? 0 : t.length;
+        return new ValueIterator<K,V>(t, f, 0, f, this);
     }
 
-    /* ---------------- Iterator Support -------------- */
-
-    abstract class HashIterator {
-        int nextSegmentIndex;
-        int nextTableIndex;
-        HashEntry<K,V>[] currentTable;
-        HashEntry<K, V> nextEntry;
-        HashEntry<K, V> lastReturned;
-
-        HashIterator() {
-            nextSegmentIndex = segments.length - 1;
-            nextTableIndex = -1;
-            advance();
+    /**
+     * Returns the hash code value for this {@link Map}, i.e.,
+     * the sum of, for each key-value pair in the map,
+     * {@code key.hashCode() ^ value.hashCode()}.
+     *
+     * @return the hash code value for this map
+     */
+    public int hashCode() {
+        int h = 0;
+        Node<K,V>[] t;
+        if ((t = table) != null) {
+            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+            for (Node<K,V> p; (p = it.advance()) != null; )
+                h += p.key.hashCode() ^ p.val.hashCode();
         }
-
-        /**
-         * Sets nextEntry to first node of next non-empty table
-         * (in backwards order, to simplify checks).
-         */
-        final void advance() {
+        return h;
+    }
+
+    /**
+     * Returns a string representation of this map.  The string
+     * representation consists of a list of key-value mappings (in no
+     * particular order) enclosed in braces ("{@code {}}").  Adjacent
+     * mappings are separated by the characters {@code ", "} (comma
+     * and space).  Each key-value mapping is rendered as the key
+     * followed by an equals sign ("{@code =}") followed by the
+     * associated value.
+     *
+     * @return a string representation of this map
+     */
+    public String toString() {
+        Node<K,V>[] t;
+        int f = (t = table) == null ? 0 : t.length;
+        Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
+        StringBuilder sb = new StringBuilder();
+        sb.append('{');
+        Node<K,V> p;
+        if ((p = it.advance()) != null) {
             for (;;) {
-                if (nextTableIndex >= 0) {
-                    if ((nextEntry = entryAt(currentTable,
-                                             nextTableIndex--)) != null)
-                        break;
-                }
-                else if (nextSegmentIndex >= 0) {
-                    Segment<K,V> seg = segmentAt(segments, nextSegmentIndex--);
-                    if (seg != null && (currentTable = seg.table) != null)
-                        nextTableIndex = currentTable.length - 1;
-                }
-                else
+                K 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(' ');
             }
         }
-
-        final HashEntry<K,V> nextEntry() {
-            HashEntry<K,V> e = nextEntry;
-            if (e == null)
-                throw new NoSuchElementException();
-            lastReturned = e; // cannot assign until after null check
-            if ((nextEntry = e.next) == null)
-                advance();
-            return e;
+        return sb.append('}').toString();
+    }
+
+    /**
+     * Compares the specified object with this map for equality.
+     * Returns {@code true} if the given object is a map with the same
+     * mappings as this map.  This operation may return misleading
+     * results if either map is concurrently modified during execution
+     * of this method.
+     *
+     * @param o object to be compared for equality with this map
+     * @return {@code true} if the specified object is equal to this map
+     */
+    public boolean equals(Object o) {
+        if (o != this) {
+            if (!(o instanceof Map))
+                return false;
+            Map<?,?> m = (Map<?,?>) o;
+            Node<K,V>[] t;
+            int f = (t = table) == null ? 0 : t.length;
+            Traverser<K,V> it = new Traverser<K,V>(t, f, 0, f);
+            for (Node<K,V> 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 = internalGet(mk)) == null ||
+                    (mv != v && !mv.equals(v)))
+                    return false;
+            }
         }
-
-        public final boolean hasNext() { return nextEntry != null; }
-        public final boolean hasMoreElements() { return nextEntry != null; }
-
-        public final void remove() {
-            if (lastReturned == null)
-                throw new IllegalStateException();
-            ConcurrentHashMap.this.remove(lastReturned.key);
-            lastReturned = null;
-        }
+        return true;
     }
 
-    final class KeyIterator
-        extends HashIterator
-        implements Iterator<K>, Enumeration<K>
-    {
-        public final K next()        { return super.nextEntry().key; }
-        public final K nextElement() { return super.nextEntry().key; }
+    /* ---------------- Serialization Support -------------- */
+
+    /**
+     * Stripped-down version of helper class used in previous version,
+     * declared for the sake of serialization compatibility
+     */
+    static class Segment<K,V> extends ReentrantLock implements Serializable {
+        private static final long serialVersionUID = 2249069246763182397L;
+        final float loadFactor;
+        Segment(float lf) { this.loadFactor = lf; }
     }
 
-    final class ValueIterator
-        extends HashIterator
-        implements Iterator<V>, Enumeration<V>
-    {
-        public final V next()        { return super.nextEntry().value; }
-        public final V nextElement() { return super.nextEntry().value; }
-    }
-
-    /**
-     * Custom Entry class used by EntryIterator.next(), that relays
-     * setValue changes to the underlying map.
-     */
-    final class WriteThroughEntry
-        extends AbstractMap.SimpleEntry<K,V>
-    {
-        static final long serialVersionUID = 7249069246763182397L;
-
-        WriteThroughEntry(K k, V v) {
-            super(k,v);
-        }
-
-        /**
-         * Sets our entry's value and writes through to the map. The
-         * value to return is somewhat arbitrary here. Since a
-         * WriteThroughEntry does 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 = super.setValue(value);
-            ConcurrentHashMap.this.put(getKey(), value);
-            return v;
-        }
-    }
-
-    final class EntryIterator
-        extends HashIterator
-        implements Iterator<Entry<K,V>>
-    {
-        public Map.Entry<K,V> next() {
-            HashEntry<K,V> e = super.nextEntry();
-            return new WriteThroughEntry(e.key, e.value);
-        }
-    }
-
-    final class KeySet extends AbstractSet<K> {
-        public Iterator<K> iterator() {
-            return new KeyIterator();
-        }
-        public int size() {
-            return ConcurrentHashMap.this.size();
-        }
-        public boolean isEmpty() {
-            return ConcurrentHashMap.this.isEmpty();
-        }
-        public boolean contains(Object o) {
-            return ConcurrentHashMap.this.containsKey(o);
-        }
-        public boolean remove(Object o) {
-            return ConcurrentHashMap.this.remove(o) != null;
-        }
-        public void clear() {
-            ConcurrentHashMap.this.clear();
-        }
-    }
-
-    final class Values extends AbstractCollection<V> {
-        public Iterator<V> iterator() {
-            return new ValueIterator();
-        }
-        public int size() {
-            return ConcurrentHashMap.this.size();
-        }
-        public boolean isEmpty() {
-            return ConcurrentHashMap.this.isEmpty();
-        }
-        public boolean contains(Object o) {
-            return ConcurrentHashMap.this.containsValue(o);
-        }
-        public void clear() {
-            ConcurrentHashMap.this.clear();
-        }
-    }
-
-    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
-        public Iterator<Map.Entry<K,V>> iterator() {
-            return new EntryIterator();
-        }
-        public boolean contains(Object o) {
-            if (!(o instanceof Map.Entry))
-                return false;
-            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
-            V v = ConcurrentHashMap.this.get(e.getKey());
-            return v != null && v.equals(e.getValue());
-        }
-        public boolean remove(Object o) {
-            if (!(o instanceof Map.Entry))
-                return false;
-            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
-            return ConcurrentHashMap.this.remove(e.getKey(), e.getValue());
-        }
-        public int size() {
-            return ConcurrentHashMap.this.size();
-        }
-        public boolean isEmpty() {
-            return ConcurrentHashMap.this.isEmpty();
-        }
-        public void clear() {
-            ConcurrentHashMap.this.clear();
-        }
-    }
-
-    /* ---------------- Serialization Support -------------- */
-
     /**
      * Saves the state of the {@code ConcurrentHashMap} instance to a
      * stream (i.e., serializes it).
@@ -1448,119 +3169,2733 @@
      * The key-value mappings are emitted in no particular order.
      */
     private void writeObject(java.io.ObjectOutputStream s)
-            throws java.io.IOException {
-        // force all segments for serialization compatibility
-        for (int k = 0; k < segments.length; ++k)
-            ensureSegment(k);
-        s.defaultWriteObject();
-
-        final Segment<K,V>[] segments = this.segments;
-        for (int k = 0; k < segments.length; ++k) {
-            Segment<K,V> seg = segmentAt(segments, k);
-            seg.lock();
-            try {
-                HashEntry<K,V>[] tab = seg.table;
-                for (int i = 0; i < tab.length; ++i) {
-                    HashEntry<K,V> e;
-                    for (e = entryAt(tab, i); e != null; e = e.next) {
-                        s.writeObject(e.key);
-                        s.writeObject(e.value);
-                    }
-                }
-            } finally {
-                seg.unlock();
+        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;
+        Segment<K,V>[] segments = (Segment<K,V>[])
+            new Segment<?,?>[DEFAULT_CONCURRENCY_LEVEL];
+        for (int i = 0; i < segments.length; ++i)
+            segments[i] = new Segment<K,V>(LOAD_FACTOR);
+        s.putFields().put("segments", segments);
+        s.putFields().put("segmentShift", segmentShift);
+        s.putFields().put("segmentMask", segmentMask);
+        s.writeFields();
+
+        Node<K,V>[] t;
+        if ((t = table) != null) {
+            Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
+            for (Node<K,V> p; (p = it.advance()) != null; ) {
+                s.writeObject(p.key);
+                s.writeObject(p.val);
             }
         }
         s.writeObject(null);
         s.writeObject(null);
+        segments = null; // throw away
     }
 
     /**
      * Reconstitutes the instance from a stream (that is, deserializes it).
      * @param s the stream
      */
-    @SuppressWarnings("unchecked")
     private void readObject(java.io.ObjectInputStream s)
-            throws java.io.IOException, ClassNotFoundException {
-        // Don't call defaultReadObject()
-        ObjectInputStream.GetField oisFields = s.readFields();
-        final Segment<K,V>[] oisSegments = (Segment<K,V>[])oisFields.get("segments", null);
-
-        final int ssize = oisSegments.length;
-        if (ssize < 1 || ssize > MAX_SEGMENTS
-            || (ssize & (ssize-1)) != 0 )  // ssize not power of two
-            throw new java.io.InvalidObjectException("Bad number of segments:"
-                                                     + ssize);
-        int sshift = 0, ssizeTmp = ssize;
-        while (ssizeTmp > 1) {
-            ++sshift;
-            ssizeTmp >>>= 1;
+        throws java.io.IOException, ClassNotFoundException {
+        s.defaultReadObject();
+
+        // Create all nodes, then place in table once size is known
+        long size = 0L;
+        Node<K,V> p = null;
+        for (;;) {
+            K k = (K) s.readObject();
+            V v = (V) s.readObject();
+            if (k != null && v != null) {
+                int h = spread(k.hashCode());
+                p = new Node<K,V>(h, k, v, p);
+                ++size;
+            }
+            else
+                break;
         }
-        UNSAFE.putIntVolatile(this, SEGSHIFT_OFFSET, 32 - sshift);
-        UNSAFE.putIntVolatile(this, SEGMASK_OFFSET, ssize - 1);
-        UNSAFE.putObjectVolatile(this, SEGMENTS_OFFSET, oisSegments);
-
-        // set hashMask
-        UNSAFE.putIntVolatile(this, HASHSEED_OFFSET,
-                 sun.misc.Hashing.randomHashSeed(this));
-
-        // Re-initialize segments to be minimally sized, and let grow.
-        int cap = MIN_SEGMENT_TABLE_CAPACITY;
-        final Segment<K,V>[] segments = this.segments;
-        for (int k = 0; k < segments.length; ++k) {
-            Segment<K,V> seg = segments[k];
-            if (seg != null) {
-                seg.threshold = (int)(cap * seg.loadFactor);
-                seg.table = (HashEntry<K,V>[]) new HashEntry<?,?>[cap];
+        if (p != null) {
+            boolean init = false;
+            int n;
+            if (size >= (long)(MAXIMUM_CAPACITY >>> 1))
+                n = MAXIMUM_CAPACITY;
+            else {
+                int sz = (int)size;
+                n = tableSizeFor(sz + (sz >>> 1) + 1);
+            }
+            int sc = sizeCtl;
+            boolean collide = false;
+            if (n > sc &&
+                U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
+                try {
+                    if (table == null) {
+                        init = true;
+                        Node<K,V>[] tab = (Node<K,V>[])new Node[n];
+                        int mask = n - 1;
+                        while (p != null) {
+                            int j = p.hash & mask;
+                            Node<K,V> next = p.next;
+                            Node<K,V> q = p.next = tabAt(tab, j);
+                            setTabAt(tab, j, p);
+                            if (!collide && q != null && q.hash == p.hash)
+                                collide = true;
+                            p = next;
+                        }
+                        table = tab;
+                        addCount(size, -1);
+                        sc = n - (n >>> 2);
+                    }
+                } finally {
+                    sizeCtl = sc;
+                }
+                if (collide) { // rescan and convert to TreeBins
+                    Node<K,V>[] tab = table;
+                    for (int i = 0; i < tab.length; ++i) {
+                        int c = 0;
+                        for (Node<K,V> e = tabAt(tab, i); e != null; e = e.next) {
+                            if (++c > TREE_THRESHOLD &&
+                                (e.key instanceof Comparable)) {
+                                replaceWithTreeBin(tab, i, e.key);
+                                break;
+                            }
+                        }
+                    }
+                }
+            }
+            if (!init) { // Can only happen if unsafely published.
+                while (p != null) {
+                    internalPut((K)p.key, p.val, false);
+                    p = p.next;
+                }
             }
         }
-
-        // Read the keys and values, and put the mappings in the table
-        for (;;) {
-            K key = (K) s.readObject();
-            V value = (V) s.readObject();
-            if (key == null)
-                break;
-            put(key, value);
+    }
+
+    // -------------------------------------------------------
+
+    // Overrides of other default Map methods
+
+    public void forEach(BiConsumer<? super K, ?