diff --git a/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java b/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java index 5bfe096893ce761374005b3681535457ba9b3dcc..9044d92b86f270f0219ad70f8b643659994a9764 100644 --- a/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java +++ b/src/share/classes/com/sun/java/util/jar/pack/UnpackerImpl.java @@ -134,7 +134,7 @@ public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker { } else { try { (new NativeUnpack(this)).run(in0, out); - } catch (UnsatisfiedLinkError ule) { + } catch (UnsatisfiedLinkError | NoClassDefFoundError ex) { // failover to java implementation (new DoUnpack()).run(in0, out); } diff --git a/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java b/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java index 732c280f7ddf6d20996a9f5be61040782c7181a6..0e08177d7f2a162626b0f5675f8684e08769f47a 100644 --- a/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java +++ b/src/share/classes/com/sun/jmx/mbeanserver/Introspector.java @@ -52,6 +52,7 @@ import javax.management.NotCompliantMBeanException; import com.sun.jmx.remote.util.EnvHelp; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; +import java.security.AccessController; import javax.management.AttributeNotFoundException; import javax.management.openmbean.CompositeData; import sun.reflect.misc.MethodUtil; @@ -64,7 +65,11 @@ import sun.reflect.misc.ReflectUtil; * @since 1.5 */ public class Introspector { - + final public static boolean ALLOW_NONPUBLIC_MBEAN; + static { + String val = AccessController.doPrivileged(new GetPropertyAction("jdk.jmx.mbeans.allowNonPublic")); + ALLOW_NONPUBLIC_MBEAN = Boolean.parseBoolean(val); + } /* * ------------------------------------------ @@ -223,11 +228,27 @@ public class Introspector { return testCompliance(baseClass, null); } + /** + * Tests the given interface class for being a compliant MXBean interface. + * A compliant MXBean interface is any publicly accessible interface + * following the {@link MXBean} conventions. + * @param interfaceClass An interface class to test for the MXBean compliance + * @throws NotCompliantMBeanException Thrown when the tested interface + * is not public or contradicts the {@link MXBean} conventions. + */ public static void testComplianceMXBeanInterface(Class interfaceClass) throws NotCompliantMBeanException { MXBeanIntrospector.getInstance().getAnalyzer(interfaceClass); } + /** + * Tests the given interface class for being a compliant MBean interface. + * A compliant MBean interface is any publicly accessible interface + * following the {@code MBean} conventions. + * @param interfaceClass An interface class to test for the MBean compliance + * @throws NotCompliantMBeanException Thrown when the tested interface + * is not public or contradicts the {@code MBean} conventions. + */ public static void testComplianceMBeanInterface(Class interfaceClass) throws NotCompliantMBeanException{ StandardMBeanIntrospector.getInstance().getAnalyzer(interfaceClass); @@ -299,18 +320,18 @@ public class Introspector { * not a JMX compliant Standard MBean. */ public static Class getStandardMBeanInterface(Class baseClass) - throws NotCompliantMBeanException { - Class current = baseClass; - Class mbeanInterface = null; - while (current != null) { - mbeanInterface = - findMBeanInterface(current, current.getName()); - if (mbeanInterface != null) break; - current = current.getSuperclass(); - } - if (mbeanInterface != null) { - return mbeanInterface; - } else { + throws NotCompliantMBeanException { + Class current = baseClass; + Class mbeanInterface = null; + while (current != null) { + mbeanInterface = + findMBeanInterface(current, current.getName()); + if (mbeanInterface != null) break; + current = current.getSuperclass(); + } + if (mbeanInterface != null) { + return mbeanInterface; + } else { final String msg = "Class " + baseClass.getName() + " is not a JMX compliant Standard MBean"; @@ -507,8 +528,11 @@ public class Introspector { } Class[] interfaces = c.getInterfaces(); for (int i = 0;i < interfaces.length; i++) { - if (interfaces[i].getName().equals(clMBeanName)) + if (interfaces[i].getName().equals(clMBeanName) && + (Modifier.isPublic(interfaces[i].getModifiers()) || + ALLOW_NONPUBLIC_MBEAN)) { return Util.cast(interfaces[i]); + } } return null; diff --git a/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java b/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java index 5e5375d09740cb2dae6b915062fd69fee958c533..d7d06a04a731e0e4d5b1d6a3a5b9a7d9cb5840f5 100644 --- a/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java +++ b/src/share/classes/com/sun/jmx/mbeanserver/MBeanAnalyzer.java @@ -28,6 +28,8 @@ package com.sun.jmx.mbeanserver; import static com.sun.jmx.mbeanserver.Util.*; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.security.AccessController; import java.util.Arrays; import java.util.Comparator; import java.util.List; @@ -50,7 +52,6 @@ import javax.management.NotCompliantMBeanException; * @since 1.6 */ class MBeanAnalyzer { - static interface MBeanVisitor { public void visitAttribute(String attributeName, M getter, @@ -107,6 +108,10 @@ class MBeanAnalyzer { if (!mbeanType.isInterface()) { throw new NotCompliantMBeanException("Not an interface: " + mbeanType.getName()); + } else if (!Modifier.isPublic(mbeanType.getModifiers()) && + !Introspector.ALLOW_NONPUBLIC_MBEAN) { + throw new NotCompliantMBeanException("Interface is not public: " + + mbeanType.getName()); } try { diff --git a/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java b/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java index 17bab9c9c70844aba28d549a945b49a083993ad3..93901d4b41f18b85ce873aaf28c6cc27320b6422 100644 --- a/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java +++ b/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java @@ -252,13 +252,12 @@ public abstract class AbstractSaslImpl { /** - * Outputs a byte array and converts + * Outputs a byte array. Can be null. */ protected static final void traceOutput(String srcClass, String srcMethod, String traceTag, byte[] output) { - if (output != null) { - traceOutput(srcClass, srcMethod, traceTag, output, 0, output.length); - } + traceOutput(srcClass, srcMethod, traceTag, output, 0, + output == null ? 0 : output.length); } protected static final void traceOutput(String srcClass, String srcMethod, @@ -274,13 +273,20 @@ public abstract class AbstractSaslImpl { lev = Level.FINEST; } - ByteArrayOutputStream out = new ByteArrayOutputStream(len); - new HexDumpEncoder().encodeBuffer( - new ByteArrayInputStream(output, offset, len), out); + String content; + + if (output != null) { + ByteArrayOutputStream out = new ByteArrayOutputStream(len); + new HexDumpEncoder().encodeBuffer( + new ByteArrayInputStream(output, offset, len), out); + content = out.toString(); + } else { + content = "NULL"; + } // Message id supplied by caller as part of traceTag logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}", - new Object[] {traceTag, new Integer(origlen), out.toString()}); + new Object[] {traceTag, new Integer(origlen), content}); } catch (Exception e) { logger.logp(Level.WARNING, srcClass, srcMethod, "SASLIMPL09:Error generating trace output: {0}", e); diff --git a/src/share/classes/java/io/File.java b/src/share/classes/java/io/File.java index 4bc75fe5099d0863de4e11f1d08014ecf3ce5e97..6bab9bb21fe7e428d40a0b381a139316bdd55af3 100644 --- a/src/share/classes/java/io/File.java +++ b/src/share/classes/java/io/File.java @@ -1910,7 +1910,7 @@ public class File } String name = prefix + Long.toString(n) + suffix; File f = new File(dir, name); - if (!name.equals(f.getName())) + if (!name.equals(f.getName()) || f.isInvalid()) throw new IOException("Unable to create temporary file"); return f; } @@ -1996,19 +1996,26 @@ public class File File tmpdir = (directory != null) ? directory : TempDirectory.location(); + SecurityManager sm = System.getSecurityManager(); File f; - try { - do { - f = TempDirectory.generateFile(prefix, suffix, tmpdir); - } while (f.exists()); - if (!f.createNewFile()) - throw new IOException("Unable to create temporary file"); - } catch (SecurityException se) { - // don't reveal temporary directory location - if (directory == null) - throw new SecurityException("Unable to create temporary file"); - throw se; - } + do { + f = TempDirectory.generateFile(prefix, suffix, tmpdir); + + if (sm != null) { + try { + sm.checkWrite(f.getPath()); + } catch (SecurityException se) { + // don't reveal temporary directory location + if (directory == null) + throw new SecurityException("Unable to create temporary file"); + throw se; + } + } + } while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0); + + if (!fs.createFileExclusively(f.getPath())) + throw new IOException("Unable to create temporary file"); + return f; } diff --git a/src/share/classes/java/lang/management/LockInfo.java b/src/share/classes/java/lang/management/LockInfo.java index 4c05ee84f0cdfff4244b30a208c581a6f737b3ff..b08bc046c3399c7e09f0aa336ac2f3872c0b4011 100644 --- a/src/share/classes/java/lang/management/LockInfo.java +++ b/src/share/classes/java/lang/management/LockInfo.java @@ -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 @@ -42,7 +42,7 @@ import sun.management.LockInfoCompositeData; * {@link ReentrantReadWriteLock ReentrantReadWriteLock} are * two examples of ownable synchronizers provided by the platform. * - *

MXBean Mapping

+ *

MXBean Mapping

* LockInfo is mapped to a {@link CompositeData CompositeData} * as specified in the {@link #from from} method. * @@ -105,7 +105,7 @@ public class LockInfo { * given {@code CompositeData}. * The given {@code CompositeData} must contain the following attributes: *
- * + *
* * * diff --git a/src/share/classes/java/lang/management/ManagementFactory.java b/src/share/classes/java/lang/management/ManagementFactory.java index 384cf4cda069f38efa94e1b744531f0da14fcba0..6e00706ccd04ed87a9cc440c439a0aa81540d07e 100644 --- a/src/share/classes/java/lang/management/ManagementFactory.java +++ b/src/share/classes/java/lang/management/ManagementFactory.java @@ -61,7 +61,7 @@ import sun.management.ManagementFactoryHelper; * the management interface of a component of the Java virtual * machine. *

- *

Platform MXBeans

+ *

Platform MXBeans

*

* A platform MXBean is a managed bean that * conforms to the JMX @@ -87,7 +87,7 @@ import sun.management.ManagementFactoryHelper; * *

* An application can access a platform MXBean in the following ways: - *

1. Direct access to an MXBean interface
+ *

1. Direct access to an MXBean interface

*
*
    *
  • Get an MXBean instance by calling the @@ -107,7 +107,7 @@ import sun.management.ManagementFactoryHelper; * an MXBean of another running virtual machine. *
  • *
- *
2. Indirect access to an MXBean interface via MBeanServer
+ *

2. Indirect access to an MXBean interface via MBeanServer

*
    *
  • Go through the platform {@code MBeanServer} to access MXBeans * locally or a specific MBeanServerConnection to access @@ -135,7 +135,7 @@ import sun.management.ManagementFactoryHelper; * interfaces: * *
    - *
Attribute NameType
+ *
* * * @@ -178,7 +178,7 @@ import sun.management.ManagementFactoryHelper; * the following management interfaces. * *
- *
Management InterfaceObjectName
+ *
* * * @@ -195,7 +195,7 @@ import sun.management.ManagementFactoryHelper; * A Java virtual machine may have one or more instances of the following * management interfaces. *
- *
Management InterfaceObjectName
+ *
* * * @@ -561,6 +561,12 @@ public class ManagementFactory { * in the format of {@link ObjectName ObjectName}. * @param mxbeanInterface the MXBean interface to be implemented * by the proxy. + * @param an {@code mxbeanInterface} type parameter + * + * @return a proxy for a platform MXBean interface of a + * given MXBean name + * that forwards its method calls through the given + * MBeanServerConnection, or {@code null} if not exist. * * @throws IllegalArgumentException if *
    @@ -635,6 +641,7 @@ public class ManagementFactory { * @param mxbeanInterface a management interface for a platform * MXBean with one single instance in the Java virtual machine * if implemented. + * @param an {@code mxbeanInterface} type parameter * * @return the platform MXBean that implements * {@code mxbeanInterface}, or {@code null} if not exist. @@ -670,6 +677,7 @@ public class ManagementFactory { * * @param mxbeanInterface a management interface for a platform * MXBean + * @param an {@code mxbeanInterface} type parameter * * @return the list of platform MXBeans that implement * {@code mxbeanInterface}. @@ -707,6 +715,7 @@ public class ManagementFactory { * @param mxbeanInterface a management interface for a platform * MXBean with one single instance in the Java virtual machine * being monitored, if implemented. + * @param an {@code mxbeanInterface} type parameter * * @return the platform MXBean proxy for * forwarding the method calls of the {@code mxbeanInterface} @@ -750,6 +759,7 @@ public class ManagementFactory { * @param connection the {@code MBeanServerConnection} to forward to. * @param mxbeanInterface a management interface for a platform * MXBean + * @param an {@code mxbeanInterface} type parameter * * @return the list of platform MXBean proxies for * forwarding the method calls of the {@code mxbeanInterface} diff --git a/src/share/classes/java/lang/management/MemoryMXBean.java b/src/share/classes/java/lang/management/MemoryMXBean.java index a18748991c11a77189c028bcf6bf4f7a1f73daaa..356873d842c0594b8960dc6d3d19044ea050f200 100644 --- a/src/share/classes/java/lang/management/MemoryMXBean.java +++ b/src/share/classes/java/lang/management/MemoryMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, 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 @@ -49,11 +49,11 @@ import javax.management.openmbean.CompositeData; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

    Memory

    + *

    Memory

    * The memory system of the Java virtual machine manages * the following kinds of memory: * - *

    1. Heap

    + *

    1. Heap

    * The Java virtual machine has a heap that is the runtime * data area from which memory for all class instances and arrays * are allocated. It is created at the Java virtual machine start-up. @@ -63,7 +63,7 @@ import javax.management.openmbean.CompositeData; *

    The heap may be of a fixed size or may be expanded and shrunk. * The memory for the heap does not need to be contiguous. * - *

    2. Non-Heap Memory

    + *

    2. Non-Heap Memory

    * The Java virtual machine manages memory other than the heap * (referred as non-heap memory). * @@ -87,7 +87,7 @@ import javax.management.openmbean.CompositeData; * machine code translated from the Java virtual machine code for * high performance. * - *

    Memory Pools and Memory Managers

    + *

    Memory Pools and Memory Managers

    * {@link MemoryPoolMXBean Memory pools} and * {@link MemoryManagerMXBean memory managers} are the abstract entities * that monitor and manage the memory system @@ -105,7 +105,7 @@ import javax.management.openmbean.CompositeData; * add or remove memory managers during execution. * A memory pool can be managed by more than one memory manager. * - *

    Memory Usage Monitoring

    + *

    Memory Usage Monitoring

    * * Memory usage is a very important monitoring attribute for the memory system. * The memory usage, for example, could indicate: @@ -131,7 +131,7 @@ import javax.management.openmbean.CompositeData; * certain threshold. It is not intended for an application to detect * and recover from a low memory condition. * - *

    Notifications

    + *

    Notifications

    * *

    This MemoryMXBean is a * {@link javax.management.NotificationEmitter NotificationEmitter} @@ -169,7 +169,7 @@ import javax.management.openmbean.CompositeData; * MemoryNotificationInfo}. * *


    - *

    NotificationEmitter

    + *

    NotificationEmitter

    * The MemoryMXBean object returned by * {@link ManagementFactory#getMemoryMXBean} implements * the {@link javax.management.NotificationEmitter NotificationEmitter} diff --git a/src/share/classes/java/lang/management/MemoryNotificationInfo.java b/src/share/classes/java/lang/management/MemoryNotificationInfo.java index 3b0b156ee302651161a316573531170e5a303c1b..0c45555ee2eab7c6680ea27e3520ee9981c14083 100644 --- a/src/share/classes/java/lang/management/MemoryNotificationInfo.java +++ b/src/share/classes/java/lang/management/MemoryNotificationInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2006, 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 @@ -212,7 +212,7 @@ public class MemoryNotificationInfo { * The given CompositeData must contain * the following attributes: *
    - *
Management InterfaceObjectName
+ *
* * * diff --git a/src/share/classes/java/lang/management/MemoryPoolMXBean.java b/src/share/classes/java/lang/management/MemoryPoolMXBean.java index bcd7c5559b04febc2fb0dcab7ba4179b82e2733c..82aa1fcda87f961551faf24d69c626f3b68f29bd 100644 --- a/src/share/classes/java/lang/management/MemoryPoolMXBean.java +++ b/src/share/classes/java/lang/management/MemoryPoolMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, 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 @@ -49,7 +49,7 @@ package java.lang.management; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

Memory Type

+ *

Memory Type

*

The Java virtual machine has a heap for object allocation and also * maintains non-heap memory for the method area and the Java virtual * machine execution. The Java virtual machine can have one or more @@ -60,7 +60,7 @@ package java.lang.management; *

  • {@link MemoryType#NON_HEAP non-heap}
  • * * - *

    Memory Usage Monitoring

    + *

    Memory Usage Monitoring

    * * A memory pool has the following attributes: *
      @@ -71,7 +71,7 @@ package java.lang.management; * (only supported by some garbage-collected memory pools) *
    * - *

    1. Memory Usage

    + *

    1. Memory Usage

    * * The {@link #getUsage} method provides an estimate * of the current usage of a memory pool. @@ -86,14 +86,14 @@ package java.lang.management; * the current memory usage. An implementation should document when * this is the case. * - *

    2. Peak Memory Usage

    + *

    2. Peak Memory Usage

    * * The Java virtual machine maintains the peak memory usage of a memory * pool since the virtual machine was started or the peak was reset. * The peak memory usage is returned by the {@link #getPeakUsage} method * and reset by calling the {@link #resetPeakUsage} method. * - *

    3. Usage Threshold

    + *

    3. Usage Threshold

    * * Each memory pool has a manageable attribute * called the usage threshold which has a default value supplied @@ -304,7 +304,7 @@ package java.lang.management; * * * - *

    4. Collection Usage Threshold

    + *

    4. Collection Usage Threshold

    * * Collection usage threshold is a manageable attribute only applicable * to some garbage-collected memory pools. diff --git a/src/share/classes/java/lang/management/MemoryUsage.java b/src/share/classes/java/lang/management/MemoryUsage.java index 4dc23c0fe4615e99f6a972c61f3451f7390997a8..bbb75a2648451dc1e70e45bfd6a25b478c67165d 100644 --- a/src/share/classes/java/lang/management/MemoryUsage.java +++ b/src/share/classes/java/lang/management/MemoryUsage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, 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 @@ -36,8 +36,7 @@ import sun.management.MemoryUsageCompositeData; * the heap or non-heap memory of the Java virtual machine as a whole. * *

    A MemoryUsage object contains four values: - *

      - *
    Attribute NameType
    + *
    * * * * *
    init represents the initial amount of memory (in bytes) that @@ -78,7 +77,6 @@ import sun.management.MemoryUsageCompositeData; *
    - * * * Below is a picture showing an example of a memory pool: *

    @@ -98,7 +96,7 @@ import sun.management.MemoryUsageCompositeData; * max * * - *

    MXBean Mapping

    + *

    MXBean Mapping

    * MemoryUsage is mapped to a {@link CompositeData CompositeData} * with attributes as specified in the {@link #from from} method. * @@ -254,7 +252,7 @@ public class MemoryUsage { * must contain the following attributes: *

    *

    - * + *
    * * * diff --git a/src/share/classes/java/lang/management/MonitorInfo.java b/src/share/classes/java/lang/management/MonitorInfo.java index 658be133fdae7d1eeb5e3890630f6007f0c986c9..e97a3173b9e0f76bfbf71f8a4572470e75f4d74d 100644 --- a/src/share/classes/java/lang/management/MonitorInfo.java +++ b/src/share/classes/java/lang/management/MonitorInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, 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 @@ -32,7 +32,7 @@ import sun.management.MonitorInfoCompositeData; * Information about an object monitor lock. An object monitor is locked * when entering a synchronization block or method on that object. * - *

    MXBean Mapping

    + *

    MXBean Mapping

    * MonitorInfo is mapped to a {@link CompositeData CompositeData} * with attributes as specified in * the {@link #from from} method. @@ -106,7 +106,7 @@ public class MonitorInfo extends LockInfo { * * mapped type for the {@link LockInfo} class: *
    - *
    Attribute NameType
    + *
    * * * diff --git a/src/share/classes/java/lang/management/RuntimeMXBean.java b/src/share/classes/java/lang/management/RuntimeMXBean.java index e4142d3e439ad77d39426edf50436076e74bc7f8..0e680fdf04e873156f9fa956213e6ac244a1d0aa 100644 --- a/src/share/classes/java/lang/management/RuntimeMXBean.java +++ b/src/share/classes/java/lang/management/RuntimeMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, 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 @@ -272,7 +272,7 @@ public interface RuntimeMXBean extends PlatformManagedObject { * *

    * MBeanServer access:
    - * The mapped type of List is String[]. + * The mapped type of {@code List} is String[]. * * @return a list of String objects; each element * is an argument passed to the Java virtual machine. @@ -312,7 +312,7 @@ public interface RuntimeMXBean extends PlatformManagedObject { * {@link javax.management.openmbean.TabularData TabularData} * with two items in each row as follows: *

    - *
    Attribute NameType
    + *
    * * * diff --git a/src/share/classes/java/lang/management/ThreadInfo.java b/src/share/classes/java/lang/management/ThreadInfo.java index 676b698f5a2f93f42762c92967ff07bbc88c8027..e6f80b2eb23f5b309ed584bf92e1f74eb2b38cf7 100644 --- a/src/share/classes/java/lang/management/ThreadInfo.java +++ b/src/share/classes/java/lang/management/ThreadInfo.java @@ -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 @@ -33,13 +33,13 @@ import static java.lang.Thread.State.*; /** * Thread information. ThreadInfo contains the information * about a thread including: - *

    General thread information

    + *

    General thread information

    *
      *
    • Thread ID.
    • *
    • Name of the thread.
    • *
    * - *

    Execution information

    + *

    Execution information

    *
      *
    • Thread state.
    • *
    • The object upon which the thread is blocked due to: @@ -652,7 +652,7 @@ public class ThreadInfo { * The given CompositeData must contain the following attributes * unless otherwise specified below: *
      - *
    Item NameItem Type
    + *
    * * * @@ -722,7 +722,7 @@ public class ThreadInfo { * Each element is a CompositeData representing * StackTraceElement containing the following attributes: *
    - *
    Attribute NameType
    + *
    * * * diff --git a/src/share/classes/java/lang/management/ThreadMXBean.java b/src/share/classes/java/lang/management/ThreadMXBean.java index 30251d51f602a1101fc38fb19cde97a6cca3b47f..02a87dcf6d374d41b5469ceb2857c05bf9d666cf 100644 --- a/src/share/classes/java/lang/management/ThreadMXBean.java +++ b/src/share/classes/java/lang/management/ThreadMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, 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 @@ -49,7 +49,7 @@ import java.util.Map; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

    Thread ID

    + *

    Thread ID

    * Thread ID is a positive long value returned by calling the * {@link java.lang.Thread#getId} method for a thread. * The thread ID is unique during its lifetime. When a thread @@ -58,7 +58,7 @@ import java.util.Map; *

    Some methods in this interface take a thread ID or an array * of thread IDs as the input parameter and return per-thread information. * - *

    Thread CPU time

    + *

    Thread CPU time

    * A Java virtual machine implementation may support measuring * the CPU time for the current thread, for any thread, or for no threads. * @@ -83,7 +83,7 @@ import java.util.Map; * Enabling thread CPU measurement could be expensive in some * Java virtual machine implementations. * - *

    Thread Contention Monitoring

    + *

    Thread Contention Monitoring

    * Some Java virtual machines may support thread contention monitoring. * When thread contention monitoring is enabled, the accumulated elapsed * time that the thread has blocked for synchronization or waited for @@ -96,7 +96,7 @@ import java.util.Map; * {@link #setThreadContentionMonitoringEnabled} method can be used to enable * thread contention monitoring. * - *

    Synchronization Information and Deadlock Detection

    + *

    Synchronization Information and Deadlock Detection

    * Some Java virtual machines may support monitoring of * {@linkplain #isObjectMonitorUsageSupported object monitor usage} and * {@linkplain #isSynchronizerUsageSupported ownable synchronizer usage}. diff --git a/src/share/classes/java/math/BigDecimal.java b/src/share/classes/java/math/BigDecimal.java index 944f8a79fbe9faf983b9e1a01d613e768b10b2e2..1a7ca8112262d34709df97bb5d5fc7a6f8931f58 100644 --- a/src/share/classes/java/math/BigDecimal.java +++ b/src/share/classes/java/math/BigDecimal.java @@ -2592,14 +2592,18 @@ public class BigDecimal extends Number implements Comparable { * the {@code BigDecimal} value {@code 600.0}, which has * [{@code BigInteger}, {@code scale}] components equals to * [6000, 1], yields {@code 6E2} with [{@code BigInteger}, - * {@code scale}] components equals to [6, -2] + * {@code scale}] components equals to [6, -2]. If + * this BigDecimal is numerically equal to zero, then + * {@code BigDecimal.ZERO} is returned. * * @return a numerically equal {@code BigDecimal} with any * trailing zeros removed. * @since 1.5 */ public BigDecimal stripTrailingZeros() { - if(intCompact!=INFLATED) { + if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) { + return BigDecimal.ZERO; + } else if (intCompact != INFLATED) { return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE); } else { return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE); diff --git a/src/share/classes/java/net/CookieStore.java b/src/share/classes/java/net/CookieStore.java index a8232d2930c5b7d6f38c163c580b106cb875b265..89b9c41dd01a717dc39b7bd845dc03b6ae6b8eaa 100644 --- a/src/share/classes/java/net/CookieStore.java +++ b/src/share/classes/java/net/CookieStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 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 @@ -75,6 +75,8 @@ public interface CookieStore { * @return an immutable list of HttpCookie, * return empty list if no cookies match the given URI * + * @param uri the uri associated with the cookies to be returned + * * @throws NullPointerException if uri is null * * @see #add diff --git a/src/share/classes/java/net/HttpURLPermission.java b/src/share/classes/java/net/HttpURLPermission.java index 55d37fda8ca2d7a54e0370d8eda697dbf5fb672d..4e038bc739e54a2b92595fbca0e272258d7797aa 100644 --- a/src/share/classes/java/net/HttpURLPermission.java +++ b/src/share/classes/java/net/HttpURLPermission.java @@ -47,6 +47,7 @@ import java.security.Permission; * in {@link java.io.FilePermission}. There are three different ways * as the following examples show: *
    Attribute NameType
    + * * * * @@ -57,7 +58,7 @@ import java.security.Permission; * which only differ in the final path component, represented by the '*'. * * - * *
    URL Examples
    Example urlDescription
    http://www.oracle.com/a/b/c.htmlA url which identifies a specific (single) resource
    http://www.oracle.com/a/b/- + *
    http://www.oracle.com/a/b/-The '-' character refers to all resources recursively below the * preceding path (eg. http://www.oracle.com/a/b/c/d/e.html matches this * example). @@ -164,6 +165,8 @@ public final class HttpURLPermission extends Permission { * methods and request headers by invoking the two argument * constructor as follows: HttpURLPermission(url, "*:*") * + * @param url the url string + * * @throws IllegalArgumentException if url does not result in a valid {@link URI} */ public HttpURLPermission(String url) { @@ -204,11 +207,10 @@ public final class HttpURLPermission extends Permission { *
  • if the path or paths specified by p's url are contained in the * set of paths specified by this's url, then return true *
  • otherwise, return false
  • - * - *

    - * Some examples of how paths are matched are shown below: - *

    - * + * + *

    Some examples of how paths are matched are shown below: + *

    + * * * * diff --git a/src/share/classes/java/net/Inet4Address.java b/src/share/classes/java/net/Inet4Address.java index 529257fa90dd8b0cd5127c83294dbffbbaaba569..6c59a692f825933df8d0390a39fc0b050e5dc560 100644 --- a/src/share/classes/java/net/Inet4Address.java +++ b/src/share/classes/java/net/Inet4Address.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -36,7 +36,7 @@ import java.io.ObjectStreamException; * and RFC 2365: * Administratively Scoped IP Multicast * - *

    Textual representation of IP addresses

    + *

    Textual representation of IP addresses

    * * Textual representation of IPv4 address used as input to methods * takes one of the following forms: diff --git a/src/share/classes/java/net/Inet6Address.java b/src/share/classes/java/net/Inet6Address.java index 4a2d4e224732e86960bda4987c0aebeaa76be53a..169a180de11b311a12999649fc0ee1a79cd052fa 100644 --- a/src/share/classes/java/net/Inet6Address.java +++ b/src/share/classes/java/net/Inet6Address.java @@ -35,7 +35,7 @@ import java.util.Enumeration; * Defined by * RFC 2373: IP Version 6 Addressing Architecture. * - *

    Textual representation of IP addresses

    + *

    Textual representation of IP addresses

    * * Textual representation of IPv6 address used as input to methods * takes one of the following forms: @@ -156,7 +156,7 @@ import java.util.Enumeration; * system. Usually, the numeric values can be determined through administration * tools on the system. Each interface may have multiple values, one for each * scope. If the scope is unspecified, then the default value used is zero. - *

  • As a string. This must be the exact string that is returned by + *
  • As a string. This must be the exact string that is returned by * {@link java.net.NetworkInterface#getName()} for the particular interface in * question. When an Inet6Address is created in this way, the numeric scope-id * is determined at the time the object is created by querying the relevant diff --git a/src/share/classes/java/net/InetAddress.java b/src/share/classes/java/net/InetAddress.java index 1154c9a80f40450fc05c690895a79709b297aa9f..aa5ef16705de5e5cea3df04ab96bfb6deacac5cb 100644 --- a/src/share/classes/java/net/InetAddress.java +++ b/src/share/classes/java/net/InetAddress.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -65,7 +65,7 @@ import sun.net.spi.nameservice.*; * with a host name or whether it has already done reverse host name * resolution). * - *

    Address types

    + *

    Address types

    * *
  • Examples of Path Matching
    this's pathp's pathmatch
    /a/b/a/byes
    /a/b/*/a/b/cyes
    * @@ -165,7 +165,6 @@ import sun.net.spi.nameservice.*; *

    * A value of -1 indicates "cache forever". * - *

    *

    networkaddress.cache.negative.ttl (default: 10)
    *
    Indicates the caching policy for un-successful name lookups * from the name service. The value is specified as as integer to diff --git a/src/share/classes/java/net/ProtocolFamily.java b/src/share/classes/java/net/ProtocolFamily.java index c6aa95b186161b40babe0903fca1108393867a94..5d02326db18d6c97c3417c25430b0e083dcab74f 100644 --- a/src/share/classes/java/net/ProtocolFamily.java +++ b/src/share/classes/java/net/ProtocolFamily.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -34,6 +34,8 @@ package java.net; public interface ProtocolFamily { /** * Returns the name of the protocol family. + * + * @return the name of the protocol family */ String name(); } diff --git a/src/share/classes/java/net/SocketOption.java b/src/share/classes/java/net/SocketOption.java index cfa4616bcefa0334b5e7008ef7c402322422c608..2ccf57f5f33b2d59050cbc0641101e5f9007ff9a 100644 --- a/src/share/classes/java/net/SocketOption.java +++ b/src/share/classes/java/net/SocketOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -45,11 +45,15 @@ public interface SocketOption { /** * Returns the name of the socket option. + * + * @return the name of the socket option */ String name(); /** * Returns the type of the socket option value. + * + * @return the type of the socket option value */ Class type(); } diff --git a/src/share/classes/java/net/URI.java b/src/share/classes/java/net/URI.java index ed90f090c2995836d59ccbb373b358c41335e566..643c8af8a71a4ecf27e294838bff98575ed71da8 100644 --- a/src/share/classes/java/net/URI.java +++ b/src/share/classes/java/net/URI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -61,13 +61,13 @@ import java.lang.NullPointerException; // for javadoc * and relativizing URI instances. Instances of this class are immutable. * * - *

    URI syntax and components

    + *

    URI syntax and components

    * * At the highest level a URI reference (hereinafter simply "URI") in string * form has the syntax * *
    - * [scheme:]scheme-specific-part[#fragment] + * [scheme:]scheme-specific-part[#fragment] *
    * * where square brackets [...] delineate optional components and the characters @@ -334,14 +334,14 @@ import java.lang.NullPointerException; // for javadoc * *
      * - *
    • The {@link #URI(java.lang.String) single-argument - * constructor} requires any illegal characters in its argument to be + *

    • The {@linkplain #URI(java.lang.String) single-argument + * constructor} requires any illegal characters in its argument to be * quoted and preserves any escaped octets and other characters that * are present.

    • * - *
    • The {@link + *

    • The {@linkplain * #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String) - * multi-argument constructors} quote illegal characters as + * multi-argument constructors} quote illegal characters as * required by the components in which they appear. The percent character * ('%') is always quoted by these constructors. Any other * characters are preserved.

    • diff --git a/src/share/classes/java/util/Collections.java b/src/share/classes/java/util/Collections.java index ad4540db14a710e9ae2ccba635f67534b4dc2f3d..56f16f6809bfacfff63045db32b9d428b939f2f1 100644 --- a/src/share/classes/java/util/Collections.java +++ b/src/share/classes/java/util/Collections.java @@ -34,6 +34,8 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; /** * This class consists exclusively of static methods that operate on or return @@ -1510,6 +1512,86 @@ public class Collections { // Need to cast to raw in order to work around a limitation in the type system super((Set)s); } + + static Consumer> entryConsumer(Consumer> action) { + return e -> action.accept(new UnmodifiableEntry<>(e)); + } + + public void forEach(Consumer> action) { + Objects.requireNonNull(action); + c.forEach(entryConsumer(action)); + } + + static final class UnmodifiableEntrySetSpliterator + implements Spliterator> { + final Spliterator> s; + + UnmodifiableEntrySetSpliterator(Spliterator> s) { + this.s = s; + } + + @Override + public boolean tryAdvance(Consumer> action) { + Objects.requireNonNull(action); + return s.tryAdvance(entryConsumer(action)); + } + + @Override + public void forEachRemaining(Consumer> action) { + Objects.requireNonNull(action); + s.forEachRemaining(entryConsumer(action)); + } + + @Override + public Spliterator> trySplit() { + Spliterator> split = s.trySplit(); + return split == null + ? null + : new UnmodifiableEntrySetSpliterator<>(split); + } + + @Override + public long estimateSize() { + return s.estimateSize(); + } + + @Override + public long getExactSizeIfKnown() { + return s.getExactSizeIfKnown(); + } + + @Override + public int characteristics() { + return s.characteristics(); + } + + @Override + public boolean hasCharacteristics(int characteristics) { + return s.hasCharacteristics(characteristics); + } + + @Override + public Comparator> getComparator() { + return s.getComparator(); + } + } + + @SuppressWarnings("unchecked") + public Spliterator> spliterator() { + return new UnmodifiableEntrySetSpliterator<>( + (Spliterator>) c.spliterator()); + } + + @Override + public Stream> stream() { + return StreamSupport.stream(spliterator()); + } + + @Override + public Stream> parallelStream() { + return StreamSupport.parallelStream(spliterator()); + } + public Iterator> iterator() { return new Iterator>() { private final Iterator> i = c.iterator(); diff --git a/src/share/classes/java/util/Formatter.java b/src/share/classes/java/util/Formatter.java index dae0b37f48b587bf54779ee645d1bdb7d0c6a4b4..5c096c63acfb66c313c541e93c2ccc6a940304aa 100644 --- a/src/share/classes/java/util/Formatter.java +++ b/src/share/classes/java/util/Formatter.java @@ -190,7 +190,7 @@ import sun.misc.FormattedFloatingDecimal; *

      The optional flags is a set of characters that modify the output * format. The set of valid flags depends on the conversion. * - *

      The optional width is a non-negative decimal integer indicating + *

      The optional width is a positive decimal integer indicating * the minimum number of characters to be written to the output. * *

      The optional precision is a non-negative decimal integer usually diff --git a/src/share/classes/java/util/Spliterator.java b/src/share/classes/java/util/Spliterator.java index 10c551a592119cb0b457fcec325933e45b67ac79..e3477cf7b7b834ee0d0111db5b182730057244c0 100644 --- a/src/share/classes/java/util/Spliterator.java +++ b/src/share/classes/java/util/Spliterator.java @@ -62,10 +62,10 @@ import java.util.function.LongConsumer; * New characteristics may be defined in the future, so implementors should not * assign meanings to unlisted values. * - *

      A Spliterator that does not report {@code IMMUTABLE} or + *

      A Spliterator that does not report {@code IMMUTABLE} or * {@code CONCURRENT} is expected to have a documented policy concerning: * when the spliterator binds to the element source; and detection of - * structural interference of the element source detected after binding. A + * structural interference of the element source detected after binding. A * late-binding Spliterator binds to the source of elements at the * point of first traversal, first split, or first query for estimated size, * rather than at the time the Spliterator is created. A Spliterator that is @@ -429,6 +429,7 @@ public interface Spliterator { * The default implementation returns true if the corresponding bits * of the given characteristics are set. * + * @param characteristics the characteristics to check for * @return {@code true} if all the specified characteristics are present, * else {@code false} */ diff --git a/src/share/classes/java/util/concurrent/ConcurrentHashMap.java b/src/share/classes/java/util/concurrent/ConcurrentHashMap.java index e62ef35916eca3e446c23bb1494e4f0ff45e4e93..08e2bd38239be56aa229fb57ad915e20759924b8 100644 --- a/src/share/classes/java/util/concurrent/ConcurrentHashMap.java +++ b/src/share/classes/java/util/concurrent/ConcurrentHashMap.java @@ -34,8 +34,9 @@ */ package java.util.concurrent; -import java.io.Serializable; + import java.io.ObjectStreamField; +import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.AbstractMap; @@ -54,8 +55,8 @@ 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.LockSupport; 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; @@ -264,10 +265,7 @@ import java.util.stream.Stream; * @param the type of keys maintained by this map * @param the type of mapped values */ -@SuppressWarnings({"unchecked", "rawtypes", "serial"}) -public class ConcurrentHashMap extends AbstractMap - implements ConcurrentMap, Serializable { - +public class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable { private static final long serialVersionUID = 7249069246763182397L; /* @@ -280,16 +278,21 @@ public class ConcurrentHashMap extends AbstractMap * 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. + * This map usually acts as a binned (bucketed) hash table. Each + * key-value mapping is held in a Node. Most nodes are instances + * of the basic Node class with hash, key, value, and next + * fields. However, various subclasses exist: TreeNodes are + * arranged in balanced trees, not lists. TreeBins hold the roots + * of sets of TreeNodes. ForwardingNodes are placed at the heads + * of bins during resizing. ReservationNodes are used as + * placeholders while establishing values in computeIfAbsent and + * related methods. The types TreeBin, ForwardingNode, and + * ReservationNode do not hold normal user keys, values, or + * hashes, and are readily distinguishable during search etc + * because they have negative hash fields and null key and value + * fields. (These special nodes are either uncommon or transient, + * so the impact of carrying around some unused fields is + * insignificant.) * * The table is lazily initialized to a power-of-two size upon the * first insertion. Each bin in the table normally contains a @@ -301,10 +304,8 @@ public class ConcurrentHashMap extends AbstractMap * * 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. + * constraints. Nodes with negative hash fields are specially + * handled or ignored in map methods. * * 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 @@ -354,15 +355,12 @@ public class ConcurrentHashMap extends AbstractMap * 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 + * designed to have identical hash codes or ones that differs only + * in masked-out high bits. So we use a secondary strategy that + * applies when the number of nodes in a bin exceeds a + * threshold. 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 @@ -428,16 +426,48 @@ public class ConcurrentHashMap extends AbstractMap * 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 + * CounterCells. 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. + * threshold (and after resizing, many fewer do so). + * + * 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 require an additional locking mechanism. While + * list traversal is always possible by readers even during + * updates, tree traversal is not, mainly because of tree-rotations + * that may change the root node and/or its linkages. TreeBins + * include a simple read-write lock mechanism parasitic on the + * main bin-synchronization strategy: Structural adjustments + * associated with an insertion or removal are already bin-locked + * (and so cannot conflict with other writers) but must wait for + * ongoing readers to finish. Since there can be only one such + * waiter, we use a simple scheme using a single "waiter" field to + * block writers. However, readers need never block. If the root + * lock is held, 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. * * Maintaining API and serialization compatibility with previous * versions of this class introduces several oddities. Mainly: We @@ -447,6 +477,13 @@ public class ConcurrentHashMap extends AbstractMap * time that we can guarantee to honor it.) We also declare an * unused "Segment" class that is instantiated in minimal form * only when serializing. + * + * This file is organized to make things a little easier to follow + * while reading than they might otherwise: First the main static + * declarations and utilities, then fields, then main public + * methods (with a few factorings of multiple public methods into + * internal ones), then sizing methods, trees, traversers, and + * bulk operations. */ /* ---------------- Constants -------------- */ @@ -489,10 +526,28 @@ public class ConcurrentHashMap extends AbstractMap /** * 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. + * bin. Bins are converted to trees when adding an element to a + * bin with at least this many nodes. The value must be greater + * than 2, and should be at least 8 to mesh with assumptions in + * tree removal about conversion back to plain bins upon + * shrinkage. */ - private static final int TREE_THRESHOLD = 8; + static final int TREEIFY_THRESHOLD = 8; + + /** + * The bin count threshold for untreeifying a (split) bin during a + * resize operation. Should be less than TREEIFY_THRESHOLD, and at + * most 6 to mesh with shrinkage detection under removal. + */ + static final int UNTREEIFY_THRESHOLD = 6; + + /** + * The smallest table capacity for which bins may be treeified. + * (Otherwise the table is resized if too many nodes in a bin.) + * The value should be at least 4 * TREEIFY_THRESHOLD to avoid + * conflicts between resizing and treeification thresholds. + */ + static final int MIN_TREEIFY_CAPACITY = 64; /** * Minimum number of rebinnings per transfer step. Ranges are @@ -506,7 +561,9 @@ public class ConcurrentHashMap extends AbstractMap /* * Encodings for Node hash fields. See above for explanation. */ - static final int MOVED = 0x80000000; // hash field for forwarding nodes + static final int MOVED = -1; // hash for forwarding nodes + static final int TREEBIN = -2; // hash for roots of trees + static final int RESERVED = -3; // hash for transient reservations static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash /** Number of CPUS, to place bounds on some sizings */ @@ -519,13 +576,162 @@ public class ConcurrentHashMap extends AbstractMap new ObjectStreamField("segmentShift", Integer.TYPE) }; + /* ---------------- Nodes -------------- */ + /** - * A padded cell for distributing counts. Adapted from LongAdder - * and Striped64. See their internal docs for explanation. + * 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. Subclasses of Node with a negative hash field + * are special, and contain null keys and values (but are never + * exported). Otherwise, keys and vals are never null. */ - @sun.misc.Contended static final class Cell { - volatile long value; - Cell(long x) { value = x; } + static class Node implements Map.Entry { + final int hash; + final K key; + volatile V val; + volatile Node next; + + Node(int hash, K key, V val, Node next) { + this.hash = hash; + this.key = key; + this.val = val; + this.next = next; + } + + public final K getKey() { return key; } + public final V getValue() { return val; } + public final int hashCode() { return key.hashCode() ^ val.hashCode(); } + public final String toString(){ return key + "=" + val; } + public final V setValue(V value) { + throw new UnsupportedOperationException(); + } + + public final boolean equals(Object o) { + Object k, v, u; Map.Entry e; + return ((o instanceof Map.Entry) && + (k = (e = (Map.Entry)o).getKey()) != null && + (v = e.getValue()) != null && + (k == key || k.equals(key)) && + (v == (u = val) || v.equals(u))); + } + + /** + * Virtualized support for map.get(); overridden in subclasses. + */ + Node find(int h, Object k) { + Node e = this; + if (k != null) { + do { + K ek; + if (e.hash == h && + ((ek = e.key) == k || (ek != null && k.equals(ek)))) + return e; + } while ((e = e.next) != null); + } + return null; + } + } + + /* ---------------- Static utilities -------------- */ + + /** + * Spreads (XORs) higher bits of hash 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.) So 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 (so don't benefit from + * spreading), and because we use trees to handle large sets of + * collisions in bins, we just XOR some shifted bits in the + * cheapest possible way to reduce systematic lossage, as well as + * to incorporate impact of the highest bits that would otherwise + * never be used in index calculations because of table bounds. + */ + static final int spread(int h) { + return (h ^ (h >>> 16)) & HASH_BITS; + } + + /** + * 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; + } + + /** + * Returns x's Class if it is of the form "class C implements + * Comparable", else null. + */ + static Class comparableClassFor(Object x) { + if (x instanceof Comparable) { + Class c; Type[] ts, as; Type t; ParameterizedType p; + if ((c = x.getClass()) == String.class) // bypass checks + return c; + if ((ts = c.getGenericInterfaces()) != null) { + for (int i = 0; i < ts.length; ++i) { + if (((t = ts[i]) instanceof ParameterizedType) && + ((p = (ParameterizedType)t).getRawType() == + Comparable.class) && + (as = p.getActualTypeArguments()) != null && + as.length == 1 && as[0] == c) // type arg is c + return c; + } + } + } + return null; + } + + /** + * Returns k.compareTo(x) if x matches kc (k's screened comparable + * class), else 0. + */ + @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable + static int compareComparables(Class kc, Object k, Object x) { + return (x == null || x.getClass() != kc ? 0 : + ((Comparable)k).compareTo(x)); + } + + /* ---------------- Table element access -------------- */ + + /* + * Volatile access methods are used for table elements as well as + * elements of in-progress next table while resizing. All uses of + * the tab arguments must be null checked by callers. All callers + * also paranoically precheck that tab's length is not zero (or an + * equivalent check), thus ensuring that any index argument taking + * the form of a hash value anded with (length - 1) is a valid + * index. Note that, to be correct wrt arbitrary concurrency + * errors by users, these checks must operate on local variables, + * which accounts for some odd-looking inline assignments below. + * Note that calls to setTabAt always occur within locked regions, + * and so in principle require only release ordering, not need + * full volatile semantics, but are currently coded as volatile + * writes to be conservative. + */ + + @SuppressWarnings("unchecked") + static final Node tabAt(Node[] tab, int i) { + return (Node)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE); + } + + static final boolean casTabAt(Node[] tab, int i, + Node c, Node v) { + return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v); + } + + static final void setTabAt(Node[] tab, int i, Node v) { + U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v); } /* ---------------- Fields -------------- */ @@ -569,951 +775,909 @@ public class ConcurrentHashMap extends AbstractMap private transient volatile int transferOrigin; /** - * Spinlock (locked via CAS) used when resizing and/or creating Cells. + * Spinlock (locked via CAS) used when resizing and/or creating CounterCells. */ private transient volatile int cellsBusy; /** * Table of counter cells. When non-null, size is a power of 2. */ - private transient volatile Cell[] counterCells; + private transient volatile CounterCell[] counterCells; // views private transient KeySetView keySet; private transient ValuesView values; private transient EntrySetView 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. - */ + /* ---------------- Public operations -------------- */ - static final Node tabAt(Node[] tab, int i) { - return (Node)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE); + /** + * Creates a new, empty map with the default initial table size (16). + */ + public ConcurrentHashMap() { } - static final boolean casTabAt(Node[] tab, int i, - Node c, Node v) { - return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v); + /** + * 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. + * @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; } - static final void setTabAt(Node[] tab, int i, Node v) { - U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v); + /** + * Creates a new map with the same mappings as the given map. + * + * @param m the map + */ + public ConcurrentHashMap(Map m) { + this.sizeCtl = DEFAULT_CAPACITY; + putAll(m); } - /* ---------------- 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. + * 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 */ - static class Node implements Map.Entry { - final int hash; - final Object key; - volatile V val; - Node next; + public ConcurrentHashMap(int initialCapacity, float loadFactor) { + this(initialCapacity, loadFactor, 1); + } - Node(int hash, Object key, V val, Node next) { - this.hash = hash; - this.key = key; - this.val = val; - this.next = next; - } + /** + * 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, + * 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; + } - 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(); - } + // Original (since JDK1.2) Map methods - 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))); - } + /** + * {@inheritDoc} + */ + public int size() { + long n = sumCount(); + return ((n < 0L) ? 0 : + (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE : + (int)n); } /** - * Exported Entry for EntryIterator + * {@inheritDoc} */ - static final class MapEntry implements Map.Entry { - final K key; // non-null - V val; // non-null - final ConcurrentHashMap map; - MapEntry(K key, V val, ConcurrentHashMap map) { - this.key = key; - this.val = val; - this.map = map; - } - public K getKey() { return key; } - public V getValue() { return val; } - public int hashCode() { return key.hashCode() ^ val.hashCode(); } - public String toString() { return key + "=" + val; } - - public boolean equals(Object o) { - Object k, v; Map.Entry e; - return ((o instanceof Map.Entry) && - (k = (e = (Map.Entry)o).getKey()) != null && - (v = e.getValue()) != null && - (k == key || k.equals(key)) && - (v == val || v.equals(val))); - } + public boolean isEmpty() { + return sumCount() <= 0L; // ignore transient negative values + } - /** - * Sets our entry's value and writes through to the map. The - * value to return is somewhat arbitrary here. Since we do not - * necessarily track asynchronous changes, the most recent - * "previous" value could be different from what we return (or - * could even have been removed, in which case the put will - * re-establish). We do not and cannot guarantee more. - */ - public V setValue(V value) { - if (value == null) throw new NullPointerException(); - V v = val; - val = value; - map.put(key, value); - return v; + /** + * Returns the value to which the specified key is mapped, + * or {@code null} if this map contains no mapping for the key. + * + *

      More formally, if this map contains a mapping from a key + * {@code k} to a value {@code v} such that {@code key.equals(k)}, + * then this method returns {@code v}; otherwise it returns + * {@code null}. (There can be at most one such mapping.) + * + * @throws NullPointerException if the specified key is null + */ + public V get(Object key) { + Node[] tab; Node e, p; int n, eh; K ek; + int h = spread(key.hashCode()); + if ((tab = table) != null && (n = tab.length) > 0 && + (e = tabAt(tab, (n - 1) & h)) != null) { + if ((eh = e.hash) == h) { + if ((ek = e.key) == key || (ek != null && key.equals(ek))) + return e.val; + } + else if (eh < 0) + return (p = e.find(h, key)) != null ? p.val : null; + while ((e = e.next) != null) { + if (e.hash == h && + ((ek = e.key) == key || (ek != null && key.equals(ek)))) + return e.val; + } } + return null; } - - /* ---------------- TreeBins -------------- */ - /** - * Nodes for use in TreeBins + * Tests if the specified object is a key in this table. + * + * @param key possible key + * @return {@code true} if and only if the specified object + * is a key in this table, as determined by the + * {@code equals} method; {@code false} otherwise + * @throws NullPointerException if the specified key is null */ - static final class TreeNode extends Node { - TreeNode parent; // red-black tree links - TreeNode left; - TreeNode right; - TreeNode prev; // needed to unlink next upon deletion - boolean red; - - TreeNode(int hash, Object key, V val, Node next, - TreeNode parent) { - super(hash, key, val, next); - this.parent = parent; - } + public boolean containsKey(Object key) { + return get(key) != null; } /** - * Returns a Class for the given type of the form "class C - * implements Comparable", if one exists, else null. See below - * for explanation. + * Returns {@code true} if this map maps one or more keys to the + * 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 + * specified value + * @throws NullPointerException if the specified value is null */ - 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; - } + public boolean containsValue(Object value) { + if (value == null) + throw new NullPointerException(); + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + V v; + if ((v = p.val) == value || (v != null && value.equals(v))) + return true; } } - return null; + return false; } /** - * A specialized form of red-black tree for use in bins - * whose size exceeds a threshold. + * Maps the specified key to the specified value in this table. + * Neither the key nor the value can be null. * - * 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). + *

      The value can be retrieved by calling the {@code get} method + * with a key that is equal to the original key. * - * 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. + * @param key key with which the specified value is to be associated + * @param value value to be associated with the specified key + * @return the previous value associated with {@code key}, or + * {@code null} if there was no mapping for {@code key} + * @throws NullPointerException if the specified key or value is null */ - static final class TreeBin extends StampedLock { - private static final long serialVersionUID = 2249069246763182397L; - transient TreeNode root; // root of tree - transient TreeNode first; // head of next-pointer list - - /** 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; - } - } - - /** 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; - } - } + public V put(K key, V value) { + return putVal(key, value, false); + } - /** - * Returns the TreeNode (or null if not found) for the given key - * starting at given root. - */ - final TreeNode getTreeNode(int h, Object k, TreeNode 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)k).compareTo(pk)) == 0) { - TreeNode 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; + /** Implementation for put and putIfAbsent */ + final V putVal(K key, V value, boolean onlyIfAbsent) { + if (key == null || value == null) throw new NullPointerException(); + int hash = spread(key.hashCode()); + int binCount = 0; + for (Node[] tab = table;;) { + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) + tab = initTable(); + else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { + if (casTabAt(tab, i, null, + new Node(hash, key, value, null))) + break; // no lock when adding to empty bin } - return null; - } - - /** - * 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. - */ - final V getValue(int h, Object k) { - Class cc = comparableClassFor(k.getClass()); - Node r = null; - for (Node e = first; e != null; e = e.next) { - long s; - if ((s = tryReadLock()) != 0L) { - try { - r = getTreeNode(h, k, root, cc); - } finally { - unlockRead(s); + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); + else { + V oldVal = null; + synchronized (f) { + if (tabAt(tab, i) == f) { + if (fh >= 0) { + binCount = 1; + for (Node e = f;; ++binCount) { + K ek; + if (e.hash == hash && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + oldVal = e.val; + if (!onlyIfAbsent) + e.val = value; + break; + } + Node pred = e; + if ((e = e.next) == null) { + pred.next = new Node(hash, key, + value, null); + break; + } + } + } + else if (f instanceof TreeBin) { + Node p; + binCount = 2; + if ((p = ((TreeBin)f).putTreeVal(hash, key, + value)) != null) { + oldVal = p.val; + if (!onlyIfAbsent) + p.val = value; + } + } } - break; } - else if (e.hash == h && k.equals(e.key)) { - r = e; + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); + if (oldVal != null) + return oldVal; break; } } - return r == null ? null : r.val; } + addCount(1L, binCount); + return null; + } - /** - * Finds or adds a node. - * @return null if added - */ - final TreeNode putTreeNode(int h, Object k, V v) { - Class cc = comparableClassFor(k.getClass()); - TreeNode 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)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; - } + /** + * Copies all of the mappings from the specified map to this one. + * These mappings replace any mappings that this map had for any of the + * keys currently in the specified map. + * + * @param m mappings to be stored in this map + */ + public void putAll(Map m) { + tryPresize(m.size()); + for (Map.Entry e : m.entrySet()) + putVal(e.getKey(), e.getValue(), false); + } - TreeNode f = first; - TreeNode x = first = new TreeNode(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 xp, xpp, xppl, xppr;;) { - if ((xp = x.parent) == null) { - (root = x).red = false; - break; - } - else if (!xp.red || (xpp = xp.parent) == null) { - TreeNode 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; - } - if (xp != null) { - xp.red = false; - if (xpp != null) { - xpp.red = true; - rotateRight(xpp); + /** + * Removes the key (and its corresponding value) from this map. + * This method does nothing if the key is not in the map. + * + * @param key the key that needs to be removed + * @return the previous value associated with {@code key}, or + * {@code null} if there was no mapping for {@code key} + * @throws NullPointerException if the specified key is null + */ + public V remove(Object key) { + return replaceNode(key, null, null); + } + + /** + * 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. + */ + final V replaceNode(Object key, V value, Object cv) { + int hash = spread(key.hashCode()); + for (Node[] tab = table;;) { + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0 || + (f = tabAt(tab, i = (n - 1) & hash)) == null) + break; + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); + else { + V oldVal = null; + boolean validated = false; + synchronized (f) { + if (tabAt(tab, i) == f) { + if (fh >= 0) { + validated = true; + for (Node e = f, pred = null;;) { + K ek; + if (e.hash == hash && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + V ev = e.val; + if (cv == null || cv == ev || + (ev != null && cv.equals(ev))) { + oldVal = ev; + if (value != null) + e.val = value; + else if (pred != null) + pred.next = e.next; + else + setTabAt(tab, i, e.next); + } + break; } + pred = e; + if ((e = e.next) == null) + break; } } - } - else { - 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; - } - if (xp != null) { - xp.red = false; - if (xpp != null) { - xpp.red = true; - rotateLeft(xpp); + else if (f instanceof TreeBin) { + validated = true; + TreeBin t = (TreeBin)f; + TreeNode r, p; + if ((r = t.root) != null && + (p = r.findTreeNode(hash, key, null)) != null) { + V pv = p.val; + if (cv == null || cv == pv || + (pv != null && cv.equals(pv))) { + oldVal = pv; + if (value != null) + p.val = value; + else if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); } } } } } - } - assert checkInvariants(); - return null; - } - - /** - * Removes the given node, that must be present before this - * call. This is messier than typical red-black deletion code - * because we cannot swap the contents of an interior node - * with a leaf successor that is pinned by "next" pointers - * that are accessible independently of lock. So instead we - * swap the tree linkages. - */ - final void deleteTreeNode(TreeNode p) { - TreeNode next = (TreeNode)p.next; - TreeNode 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 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 (validated) { + if (oldVal != null) { + if (value == null) + addCount(-1L, -1); + return oldVal; } - if ((s.right = pr) != null) - pr.parent = s; + break; } - 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 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; + } + return null; + } + + /** + * Removes all of the mappings from this map. + */ + public void clear() { + long delta = 0L; // negative number of deletions + int i = 0; + Node[] tab = table; + while (tab != null && i < tab.length) { + int fh; + Node f = tabAt(tab, i); + if (f == null) + ++i; + else if ((fh = f.hash) == MOVED) { + tab = helpTransfer(tab, f); + i = 0; // restart } - if (!p.red) { // rebalance, from CLR - for (TreeNode x = replacement; x != null; ) { - TreeNode 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 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 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; - } + else { + synchronized (f) { + if (tabAt(tab, i) == f) { + Node p = (fh >= 0 ? f : + (f instanceof TreeBin) ? + ((TreeBin)f).first : null); + while (p != null) { + --delta; + p = p.next; } + setTabAt(tab, i++, null); } } } - if (p == replacement) { // detach pointers - TreeNode pp; - if ((pp = p.parent) != null) { - if (p == pp.left) - pp.left = null; - else if (p == pp.right) - pp.right = null; - p.parent = null; - } - } - assert checkInvariants(); - } - - /** - * Checks linkage and balance invariants at root - */ - final boolean checkInvariants() { - TreeNode r = root; - if (r == null) - return (first == null); - else - return (first != null) && checkTreeNode(r); } + if (delta != 0L) + addCount(delta, -1); + } - /** - * Recursive invariant check - */ - final boolean checkTreeNode(TreeNode t) { - TreeNode tp = t.parent, tl = t.left, tr = t.right, - tb = t.prev, tn = (TreeNode)t.next; - if (tb != null && tb.next != t) - return false; - if (tn != null && tn.prev != t) - return false; - if (tp != null && t != tp.left && t != tp.right) - return false; - if (tl != null && (tl.parent != t || tl.hash > t.hash)) - return false; - if (tr != null && (tr.parent != t || tr.hash < t.hash)) - return false; - if (t.red && tl != null && tl.red && tr != null && tr.red) - return false; - if (tl != null && !checkTreeNode(tl)) - return false; - if (tr != null && !checkTreeNode(tr)) - return false; - return true; - } + /** + * Returns a {@link Set} view of the keys contained in this map. + * The set is backed by the map, so changes to the map are + * reflected in the set, and vice-versa. The set supports element + * removal, which removes the corresponding mapping from this 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. + * + *

      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 KeySetView keySet() { + KeySetView ks; + return (ks = keySet) != null ? ks : (keySet = new KeySetView(this, null)); } - /* ---------------- Collision reduction methods -------------- */ + /** + * Returns a {@link Collection} view of the values contained in this map. + * The collection is backed by the map, so changes to the map are + * reflected in the collection, and vice-versa. The collection + * supports element removal, which removes the corresponding + * mapping from this map, via the {@code Iterator.remove}, + * {@code Collection.remove}, {@code removeAll}, + * {@code retainAll}, and {@code clear} operations. It does not + * support the {@code add} or {@code addAll} operations. + * + *

      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 collection view + */ + public Collection values() { + ValuesView vs; + return (vs = values) != null ? vs : (values = new ValuesView(this)); + } /** - * 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. + * Returns a {@link Set} view of the mappings contained in this map. + * The set is backed by the map, so changes to the map are + * reflected in the set, and vice-versa. The set supports element + * 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. + * + *

      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 */ - private static final int spread(int h) { - h ^= (h >>> 18) ^ (h >>> 12); - return (h ^ (h >>> 10)) & HASH_BITS; + public Set> entrySet() { + EntrySetView es; + return (es = entrySet) != null ? es : (entrySet = new EntrySetView(this)); } /** - * Replaces a list bin with a tree bin if key is comparable. Call - * only when locked. + * 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 */ - private final void replaceWithTreeBin(Node[] tab, int index, Object key) { - if (tab != null && comparableClassFor(key.getClass()) != null) { - TreeBin t = new TreeBin(); - for (Node e = tabAt(tab, index); e != null; e = e.next) - t.putTreeNode(e.hash, e.key, e.val); - setTabAt(tab, index, new Node(MOVED, t, null, null)); + public int hashCode() { + int h = 0; + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) + h += p.key.hashCode() ^ p.val.hashCode(); } + return h; } - /* ---------------- 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[] tab; Node e; - if ((tab = table) != null && - (e = tabAt(tab, (tab.length - 1) & h)) != null) { + /** + * 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[] t; + int f = (t = table) == null ? 0 : t.length; + Traverser it = new Traverser(t, f, 0, f); + StringBuilder sb = new StringBuilder(); + sb.append('{'); + Node p; + if ((p = it.advance()) != null) { for (;;) { - int eh; Object ek; - if ((eh = e.hash) < 0) { - if ((ek = e.key) instanceof TreeBin) { // search TreeBin - v = ((TreeBin)ek).getValue(h, k); - break; - } - else if (!(ek instanceof Node[]) || // try new table - (e = tabAt(tab = (Node[])ek, - (tab.length - 1) & h)) == null) - break; - } - else if (eh == h && ((ek = e.key) == k || k.equals(ek))) { - v = e.val; - break; - } - else if ((e = e.next) == null) + K k = p.key; + V v = p.val; + sb.append(k == this ? "(this Map)" : k); + sb.append('='); + sb.append(v == this ? "(this Map)" : v); + if ((p = it.advance()) == null) break; + sb.append(',').append(' '); } } - return v; + return sb.append('}').toString(); } /** - * 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. + * 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 */ - private final V internalReplace(Object k, V v, Object cv) { - int h = spread(k.hashCode()); - V oldVal = null; - for (Node[] tab = table;;) { - Node 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 t = (TreeBin)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 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[])fk; + public boolean equals(Object o) { + if (o != this) { + if (!(o instanceof Map)) + return false; + Map m = (Map) o; + Node[] t; + int f = (t = table) == null ? 0 : t.length; + Traverser it = new Traverser(t, f, 0, f); + for (Node p; (p = it.advance()) != null; ) { + V val = p.val; + Object v = m.get(p.key); + if (v == null || (v != val && !v.equals(val))) + return false; } - else { - boolean validated = false; - boolean deleted = false; - synchronized (f) { - if (tabAt(tab, i) == f) { - validated = true; - for (Node 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 en = e.next; - if (pred != null) - pred.next = en; - else - setTabAt(tab, i, en); - } - } + for (Map.Entry e : m.entrySet()) { + Object mk, mv, v; + if ((mk = e.getKey()) == null || + (mv = e.getValue()) == null || + (v = get(mk)) == null || + (mv != v && !mv.equals(v))) + return false; + } + } + return true; + } + + /** + * Stripped-down version of helper class used in previous version, + * declared for the sake of serialization compatibility + */ + static class Segment extends ReentrantLock implements Serializable { + private static final long serialVersionUID = 2249069246763182397L; + final float loadFactor; + Segment(float lf) { this.loadFactor = lf; } + } + + /** + * Saves the state of the {@code ConcurrentHashMap} instance to a + * stream (i.e., serializes it). + * @param s the stream + * @serialData + * the key (Object) and value (Object) + * for each key-value mapping, followed by a null pair. + * The key-value mappings are emitted in no particular order. + */ + private void writeObject(java.io.ObjectOutputStream s) + throws java.io.IOException { + // For serialization compatibility + // Emulate segment calculation from previous version of this class + int sshift = 0; + int ssize = 1; + while (ssize < DEFAULT_CONCURRENCY_LEVEL) { + ++sshift; + ssize <<= 1; + } + int segmentShift = 32 - sshift; + int segmentMask = ssize - 1; + @SuppressWarnings("unchecked") Segment[] segments = (Segment[]) + new Segment[DEFAULT_CONCURRENCY_LEVEL]; + for (int i = 0; i < segments.length; ++i) + segments[i] = new Segment(LOAD_FACTOR); + s.putFields().put("segments", segments); + s.putFields().put("segmentShift", segmentShift); + s.putFields().put("segmentMask", segmentMask); + s.writeFields(); + + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + s.writeObject(p.key); + s.writeObject(p.val); + } + } + s.writeObject(null); + s.writeObject(null); + segments = null; // throw away + } + + /** + * Reconstitutes the instance from a stream (that is, deserializes it). + * @param s the stream + */ + private void readObject(java.io.ObjectInputStream s) + throws java.io.IOException, ClassNotFoundException { + /* + * To improve performance in typical cases, we create nodes + * while reading, then place in table once size is known. + * However, we must also validate uniqueness and deal with + * overpopulated bins while doing so, which requires + * specialized versions of putVal mechanics. + */ + sizeCtl = -1; // force exclusion for table construction + s.defaultReadObject(); + long size = 0L; + Node p = null; + for (;;) { + @SuppressWarnings("unchecked") K k = (K) s.readObject(); + @SuppressWarnings("unchecked") V v = (V) s.readObject(); + if (k != null && v != null) { + p = new Node(spread(k.hashCode()), k, v, p); + ++size; + } + else + break; + } + if (size == 0L) + sizeCtl = 0; + else { + int n; + if (size >= (long)(MAXIMUM_CAPACITY >>> 1)) + n = MAXIMUM_CAPACITY; + else { + int sz = (int)size; + n = tableSizeFor(sz + (sz >>> 1) + 1); + } + @SuppressWarnings({"rawtypes","unchecked"}) + Node[] tab = (Node[])new Node[n]; + int mask = n - 1; + long added = 0L; + while (p != null) { + boolean insertAtFront; + Node next = p.next, first; + int h = p.hash, j = h & mask; + if ((first = tabAt(tab, j)) == null) + insertAtFront = true; + else { + K k = p.key; + if (first.hash < 0) { + TreeBin t = (TreeBin)first; + if (t.putTreeVal(h, k, p.val) == null) + ++added; + insertAtFront = false; + } + else { + int binCount = 0; + insertAtFront = true; + Node q; K qk; + for (q = first; q != null; q = q.next) { + if (q.hash == h && + ((qk = q.key) == k || + (qk != null && k.equals(qk)))) { + insertAtFront = false; break; } - pred = e; - if ((e = e.next) == null) - break; + ++binCount; + } + if (insertAtFront && binCount >= TREEIFY_THRESHOLD) { + insertAtFront = false; + ++added; + p.next = first; + TreeNode hd = null, tl = null; + for (q = p; q != null; q = q.next) { + TreeNode t = new TreeNode + (q.hash, q.key, q.val, null, null); + if ((t.prev = tl) == null) + hd = t; + else + tl.next = t; + tl = t; + } + setTabAt(tab, j, new TreeBin(hd)); } } } - if (validated) { - if (deleted) - addCount(-1L, -1); - break; + if (insertAtFront) { + ++added; + p.next = first; + setTabAt(tab, j, p); } + p = next; } + table = tab; + sizeCtl = n - (n >>> 2); + baseCount = added; } - 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 + // ConcurrentMap methods + + /** + * {@inheritDoc} * - * The putAll method differs mainly in attempting to pre-allocate - * enough table space, and also more lazily performs count updates - * and checks. + * @return the previous value associated with the specified key, + * or {@code null} if there was no mapping for the key + * @throws NullPointerException if the specified key or value is null + */ + public V putIfAbsent(K key, V value) { + return putVal(key, value, true); + } + + /** + * {@inheritDoc} * - * Most of the function-accepting methods can't be factored nicely - * because they require different functional forms, so instead - * sprawl out similar mechanics. + * @throws NullPointerException if the specified key is null */ + public boolean remove(Object key, Object value) { + if (key == null) + throw new NullPointerException(); + return value != null && replaceNode(key, null, value) != null; + } - /** 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[] tab = table;;) { - int i, fh; Node 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(h, k, v, null))) - break; // no lock when adding to empty bin + /** + * {@inheritDoc} + * + * @throws NullPointerException if any of the arguments are null + */ + public boolean replace(K key, V oldValue, V newValue) { + if (key == null || oldValue == null || newValue == null) + throw new NullPointerException(); + return replaceNode(key, newValue, oldValue) != null; + } + + /** + * {@inheritDoc} + * + * @return the previous value associated with the specified key, + * or {@code null} if there was no mapping for the key + * @throws NullPointerException if the specified key or value is null + */ + public V replace(K key, V value) { + if (key == null || value == null) + throw new NullPointerException(); + return replaceNode(key, value, null); + } + + // Overrides of JDK8+ Map extension method defaults + + /** + * 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 = get(key)) == null ? defaultValue : v; + } + + public void forEach(BiConsumer action) { + if (action == null) throw new NullPointerException(); + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + action.accept(p.key, p.val); } - else if ((fh = f.hash) < 0) { - if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)fk; - long stamp = t.writeLock(); - V oldVal = null; - try { - if (tabAt(tab, i) == f) { - len = 2; - TreeNode p = t.putTreeNode(h, k, v); - if (p != null) { - oldVal = p.val; - if (!onlyIfAbsent) - p.val = v; - } - } - } finally { - t.unlockWrite(stamp); - } - if (len != 0) { - if (oldVal != null) - return oldVal; + } + } + + public void replaceAll(BiFunction function) { + if (function == null) throw new NullPointerException(); + Node[] t; + if ((t = table) != null) { + Traverser it = new Traverser(t, t.length, 0, t.length); + for (Node p; (p = it.advance()) != null; ) { + V oldValue = p.val; + for (K key = p.key;;) { + V newValue = function.apply(key, oldValue); + if (newValue == null) + throw new NullPointerException(); + if (replaceNode(key, newValue, oldValue) != null || + (oldValue = get(key)) == null) break; - } - } - else - tab = (Node[])fk; - } - else { - V oldVal = null; - synchronized (f) { - if (tabAt(tab, i) == f) { - len = 1; - for (Node 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 last = e; - if ((e = e.next) == null) { - last.next = new Node(h, k, v, null); - if (len > TREE_THRESHOLD) - replaceWithTreeBin(tab, i, k); - break; - } - } - } - } - if (len != 0) { - if (oldVal != null) - return oldVal; - break; } } } - addCount(1L, len); - return null; } - /** Implementation for computeIfAbsent */ - private final V internalComputeIfAbsent(K k, Function mf) { - if (k == null || mf == null) + /** + * 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 mappingFunction) { + if (key == null || mappingFunction == null) throw new NullPointerException(); - int h = spread(k.hashCode()); + int h = spread(key.hashCode()); V val = null; - int len = 0; + int binCount = 0; for (Node[] tab = table;;) { - Node f; int i; Object fk; - if (tab == null) + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) tab = initTable(); - else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { - Node node = new Node(h, k, null, null); - synchronized (node) { - if (casTabAt(tab, i, null, node)) { - len = 1; + else if ((f = tabAt(tab, i = (n - 1) & h)) == null) { + Node r = new ReservationNode(); + synchronized (r) { + if (casTabAt(tab, i, null, r)) { + binCount = 1; + Node node = null; try { - if ((val = mf.apply(k)) != null) - node.val = val; + if ((val = mappingFunction.apply(key)) != null) + node = new Node(h, key, val, null); } finally { - if (val == null) - setTabAt(tab, i, null); + setTabAt(tab, i, node); } } } - if (len != 0) + if (binCount != 0) break; } - else if (f.hash < 0) { - if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)fk; - long stamp = t.writeLock(); - boolean added = false; - try { - if (tabAt(tab, i) == f) { - len = 2; - Class cc = comparableClassFor(k.getClass()); - TreeNode 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; - } - } - else - tab = (Node[])fk; - } + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); else { boolean added = false; synchronized (f) { if (tabAt(tab, i) == f) { - len = 1; - for (Node e = f;; ++len) { - Object ek; V ev; - if (e.hash == h && - ((ek = e.key) == k || k.equals(ek))) { - val = e.val; - break; - } - Node last = e; - if ((e = e.next) == null) { - if ((val = mf.apply(k)) != null) { - added = true; - last.next = new Node(h, k, val, null); - if (len > TREE_THRESHOLD) - replaceWithTreeBin(tab, i, k); + if (fh >= 0) { + binCount = 1; + for (Node e = f;; ++binCount) { + K ek; V ev; + if (e.hash == h && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + val = e.val; + break; } - break; + Node pred = e; + if ((e = e.next) == null) { + if ((val = mappingFunction.apply(key)) != null) { + added = true; + pred.next = new Node(h, key, val, null); + } + break; + } + } + } + else if (f instanceof TreeBin) { + binCount = 2; + TreeBin t = (TreeBin)f; + TreeNode r, p; + if ((r = t.root) != null && + (p = r.findTreeNode(h, key, null)) != null) + val = p.val; + else if ((val = mappingFunction.apply(key)) != null) { + added = true; + t.putTreeVal(h, key, val); } } } } - if (len != 0) { + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); if (!added) return val; break; @@ -1521,384 +1685,511 @@ public class ConcurrentHashMap extends AbstractMap } } if (val != null) - addCount(1L, len); + addCount(1L, binCount); return val; } - /** Implementation for compute */ - private final V internalCompute(K k, boolean onlyIfPresent, - BiFunction mf) { - if (k == null || mf == null) - throw new NullPointerException(); - int h = spread(k.hashCode()); - V val = null; - int delta = 0; - int len = 0; + /** + * 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 remappingFunction) { + if (key == null || remappingFunction == null) + throw new NullPointerException(); + int h = spread(key.hashCode()); + V val = null; + int delta = 0; + int binCount = 0; for (Node[] tab = table;;) { - Node f; int i, fh; Object fk; - if (tab == null) + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) tab = initTable(); - else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { - if (onlyIfPresent) - break; - Node node = new Node(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 t = (TreeBin)fk; - long stamp = t.writeLock(); - try { - if (tabAt(tab, i) == f) { - len = 2; - Class cc = comparableClassFor(k.getClass()); - TreeNode 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 if ((f = tabAt(tab, i = (n - 1) & h)) == null) + break; + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); + else { + synchronized (f) { + if (tabAt(tab, i) == f) { + if (fh >= 0) { + binCount = 1; + for (Node e = f, pred = null;; ++binCount) { + K ek; + if (e.hash == h && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + val = remappingFunction.apply(key, e.val); + if (val != null) + e.val = val; else { - delta = 1; - t.putTreeNode(h, k, val); + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); } + break; } - else if (p != null) { - delta = -1; - t.deleteTreeNode(p); - } + pred = e; + if ((e = e.next) == null) + break; } } - } finally { - t.unlockWrite(stamp); - } - if (len != 0) - break; - } - else - tab = (Node[])fk; - } - else { - synchronized (f) { - if (tabAt(tab, i) == f) { - len = 1; - for (Node e = f, pred = null;; ++len) { - Object ek; - if (e.hash == h && - ((ek = e.key) == k || k.equals(ek))) { - val = mf.apply(k, e.val); + else if (f instanceof TreeBin) { + binCount = 2; + TreeBin t = (TreeBin)f; + TreeNode r, p; + if ((r = t.root) != null && + (p = r.findTreeNode(h, key, null)) != null) { + val = remappingFunction.apply(key, p.val); if (val != null) - e.val = val; + p.val = val; else { delta = -1; - Node en = e.next; - if (pred != null) - pred.next = en; - else - setTabAt(tab, i, en); - } - break; - } - pred = e; - if ((e = e.next) == null) { - if (!onlyIfPresent && - (val = mf.apply(k, null)) != null) { - pred.next = new Node(h, k, val, null); - delta = 1; - if (len > TREE_THRESHOLD) - replaceWithTreeBin(tab, i, k); + if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); } - break; } } } } - if (len != 0) + if (binCount != 0) break; } } if (delta != 0) - addCount((long)delta, len); + addCount((long)delta, binCount); return val; } - /** Implementation for merge */ - private final V internalMerge(K k, V v, - BiFunction mf) { - if (k == null || v == null || mf == null) + /** + * 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 remappingFunction) { + if (key == null || remappingFunction == null) throw new NullPointerException(); - int h = spread(k.hashCode()); + int h = spread(key.hashCode()); V val = null; int delta = 0; - int len = 0; + int binCount = 0; for (Node[] tab = table;;) { - int i; Node f; Object fk; - if (tab == null) + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) tab = initTable(); - else if ((f = tabAt(tab, i = (tab.length - 1) & h)) == null) { - if (casTabAt(tab, i, null, new Node(h, k, v, null))) { - delta = 1; - val = v; - break; - } - } - else if (f.hash < 0) { - if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)fk; - long stamp = t.writeLock(); - try { - if (tabAt(tab, i) == f) { - len = 2; - Class cc = comparableClassFor(k.getClass()); - TreeNode 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); + else if ((f = tabAt(tab, i = (n - 1) & h)) == null) { + Node r = new ReservationNode(); + synchronized (r) { + if (casTabAt(tab, i, null, r)) { + binCount = 1; + Node node = null; + try { + if ((val = remappingFunction.apply(key, null)) != null) { + delta = 1; + node = new Node(h, key, val, null); } + } finally { + setTabAt(tab, i, node); } - } finally { - t.unlockWrite(stamp); } - if (len != 0) - break; } - else - tab = (Node[])fk; + if (binCount != 0) + break; } + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); else { synchronized (f) { if (tabAt(tab, i) == f) { - len = 1; - for (Node 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; + if (fh >= 0) { + binCount = 1; + for (Node e = f, pred = null;; ++binCount) { + K ek; + if (e.hash == h && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + val = remappingFunction.apply(key, e.val); + if (val != null) + e.val = val; + else { + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); + } + break; + } + pred = e; + if ((e = e.next) == null) { + val = remappingFunction.apply(key, null); + if (val != null) { + delta = 1; + pred.next = + new Node(h, key, val, null); + } + break; + } + } + } + else if (f instanceof TreeBin) { + binCount = 1; + TreeBin t = (TreeBin)f; + TreeNode r, p; + if ((r = t.root) != null) + p = r.findTreeNode(h, key, null); + else + p = null; + V pv = (p == null) ? null : p.val; + val = remappingFunction.apply(key, pv); + if (val != null) { + if (p != null) + p.val = val; else { - delta = -1; - Node en = e.next; - if (pred != null) - pred.next = en; - else - setTabAt(tab, i, en); + delta = 1; + t.putTreeVal(h, key, val); } - break; } - pred = e; - if ((e = e.next) == null) { - delta = 1; - val = v; - pred.next = new Node(h, k, val, null); - if (len > TREE_THRESHOLD) - replaceWithTreeBin(tab, i, k); - break; + else if (p != null) { + delta = -1; + if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); } } } } - if (len != 0) + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); break; + } } } if (delta != 0) - addCount((long)delta, len); + addCount((long)delta, binCount); return val; } - /** Implementation for putAll */ - private final void internalPutAll(Map 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 entry : m.entrySet()) { - Object k; V v; - if (entry == null || (k = entry.getKey()) == null || - (v = entry.getValue()) == null) { - npe = true; + /** + * If the specified key is not already associated with a + * (non-null) value, associates it with the given value. + * Otherwise, replaces the value with the results of the given + * remapping function, or removes if {@code null}. The entire + * method invocation is performed atomically. Some attempted + * update operations on this map by other threads may be blocked + * while computation is in progress, so the computation should be + * short and simple, and must not attempt to update any other + * mappings of this Map. + * + * @param key key with which the specified value is to be associated + * @param value the value to use if absent + * @param remappingFunction the function to recompute a value if present + * @return the new value associated with the specified key, or null if none + * @throws NullPointerException if the specified key or the + * remappingFunction is null + * @throws RuntimeException or Error if the remappingFunction does so, + * in which case the mapping is unchanged + */ + public V merge(K key, V value, BiFunction remappingFunction) { + if (key == null || value == null || remappingFunction == null) + throw new NullPointerException(); + int h = spread(key.hashCode()); + V val = null; + int delta = 0; + int binCount = 0; + for (Node[] tab = table;;) { + Node f; int n, i, fh; + if (tab == null || (n = tab.length) == 0) + tab = initTable(); + else if ((f = tabAt(tab, i = (n - 1) & h)) == null) { + if (casTabAt(tab, i, null, new Node(h, key, value, null))) { + delta = 1; + val = value; break; } - int h = spread(k.hashCode()); - for (Node[] tab = table;;) { - int i; Node 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(h, k, v, null))) { - ++delta; - break; - } - } - else if ((fh = f.hash) < 0) { - if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)fk; - long stamp = t.writeLock(); - boolean validated = false; - try { - if (tabAt(tab, i) == f) { - validated = true; - Class cc = comparableClassFor(k.getClass()); - TreeNode p = t.getTreeNode(h, k, - t.root, cc); - if (p != null) - p.val = v; + } + else if ((fh = f.hash) == MOVED) + tab = helpTransfer(tab, f); + else { + synchronized (f) { + if (tabAt(tab, i) == f) { + if (fh >= 0) { + binCount = 1; + for (Node e = f, pred = null;; ++binCount) { + K ek; + if (e.hash == h && + ((ek = e.key) == key || + (ek != null && key.equals(ek)))) { + val = remappingFunction.apply(e.val, value); + if (val != null) + e.val = val; else { - ++delta; - t.putTreeNode(h, k, v); + delta = -1; + Node en = e.next; + if (pred != null) + pred.next = en; + else + setTabAt(tab, i, en); } + break; + } + pred = e; + if ((e = e.next) == null) { + delta = 1; + val = value; + pred.next = + new Node(h, key, val, null); + break; } - } finally { - t.unlockWrite(stamp); } - if (validated) - break; } - else - tab = (Node[])fk; - } - else { - int len = 0; - synchronized (f) { - if (tabAt(tab, i) == f) { - len = 1; - for (Node e = f;; ++len) { - Object ek; - if (e.hash == h && - ((ek = e.key) == k || k.equals(ek))) { - e.val = v; - break; - } - Node last = e; - if ((e = e.next) == null) { - ++delta; - last.next = new Node(h, k, v, null); - if (len > TREE_THRESHOLD) - replaceWithTreeBin(tab, i, k); - break; - } + else if (f instanceof TreeBin) { + binCount = 2; + TreeBin t = (TreeBin)f; + TreeNode r = t.root; + TreeNode p = (r == null) ? null : + r.findTreeNode(h, key, null); + val = (p == null) ? value : + remappingFunction.apply(p.val, value); + if (val != null) { + if (p != null) + p.val = val; + else { + delta = 1; + t.putTreeVal(h, key, val); } } - } - if (len != 0) { - if (len > 1) { - addCount(delta, len); - delta = 0L; + else if (p != null) { + delta = -1; + if (t.removeTreeNode(p)) + setTabAt(tab, i, untreeify(t.first)); } - break; } } } + if (binCount != 0) { + if (binCount >= TREEIFY_THRESHOLD) + treeifyBin(tab, i); + break; + } } - } finally { - if (delta != 0L) - addCount(delta, 2); } - if (npe) - throw new NullPointerException(); + if (delta != 0) + addCount((long)delta, binCount); + return val; } + // Hashtable legacy methods + /** - * Implementation for clear. Steps through each bin, removing all - * nodes. + * Legacy method testing if some key maps into the specified value + * in this table. This method is identical in functionality to + * {@link #containsValue(Object)}, and exists solely to ensure + * full compatibility with class {@link java.util.Hashtable}, + * which supported this method prior to introduction of the + * Java Collections framework. + * + * @param value a value to search for + * @return {@code true} if and only if some key maps to the + * {@code value} argument in this table as + * determined by the {@code equals} method; + * {@code false} otherwise + * @throws NullPointerException if the specified value is null */ - private final void internalClear() { - long delta = 0L; // negative number of deletions - int i = 0; - Node[] tab = table; - while (tab != null && i < tab.length) { - Node f = tabAt(tab, i); - if (f == null) - ++i; - else if (f.hash < 0) { - Object fk; - if ((fk = f.key) instanceof TreeBin) { - TreeBin t = (TreeBin)fk; - long stamp = t.writeLock(); - try { - if (tabAt(tab, i) == f) { - for (Node p = t.first; p != null; p = p.next) - --delta; - t.first = null; - t.root = null; - ++i; - } - } finally { - t.unlockWrite(stamp); - } - } - else - tab = (Node[])fk; - } - else { - synchronized (f) { - if (tabAt(tab, i) == f) { - for (Node e = f; e != null; e = e.next) - --delta; - setTabAt(tab, i, null); - ++i; - } - } - } - } - if (delta != 0L) - addCount(delta, -1); + public boolean contains(Object value) { + return containsValue(value); } - /* ---------------- Table Initialization and Resizing -------------- */ - /** - * Returns a power of two table size for the given desired capacity. - * See Hackers Delight, sec 3.2 + * Returns an enumeration of the keys in this table. + * + * @return an enumeration of the keys in this table + * @see #keySet() */ - 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; + public Enumeration keys() { + Node[] t; + int f = (t = table) == null ? 0 : t.length; + return new KeyIterator(t, f, 0, f, this); } /** - * Initializes table, using the size recorded in sizeCtl. - */ + * Returns an enumeration of the values in this table. + * + * @return an enumeration of the values in this table + * @see #values() + */ + public Enumeration elements() { + Node[] t; + int f = (t = table) == null ? 0 : t.length; + return new ValueIterator(t, f, 0, f, this); + } + + // ConcurrentHashMap-only methods + + /** + * 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 + } + + /** + * 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 KeySetView newKeySet() { + return new KeySetView + (new ConcurrentHashMap(), 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 + * @return the new set + * @since 1.8 + */ + public static KeySetView newKeySet(int initialCapacity) { + return new KeySetView + (new ConcurrentHashMap(initialCapacity), Boolean.TRUE); + } + + /** + * 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 keySet(V mappedValue) { + if (mappedValue == null) + throw new NullPointerException(); + return new KeySetView(this, mappedValue); + } + + /* ---------------- Special Nodes -------------- */ + + /** + * A node inserted at head of bins during transfer operations. + */ + static final class ForwardingNode extends Node { + final Node[] nextTable; + ForwardingNode(Node[] tab) { + super(MOVED, null, null, null); + this.nextTable = tab; + } + + Node find(int h, Object k) { + // loop to avoid arbitrarily deep recursion on forwarding nodes + outer: for (Node[] tab = nextTable;;) { + Node e; int n; + if (k == null || tab == null || (n = tab.length) == 0 || + (e = tabAt(tab, (n - 1) & h)) == null) + return null; + for (;;) { + int eh; K ek; + if ((eh = e.hash) == h && + ((ek = e.key) == k || (ek != null && k.equals(ek)))) + return e; + if (eh < 0) { + if (e instanceof ForwardingNode) { + tab = ((ForwardingNode)e).nextTable; + continue outer; + } + else + return e.find(h, k); + } + if ((e = e.next) == null) + return null; + } + } + } + } + + /** + * A place-holder node used in computeIfAbsent and compute + */ + static final class ReservationNode extends Node { + ReservationNode() { + super(RESERVED, null, null, null); + } + + Node find(int h, Object k) { + return null; + } + } + + /* ---------------- Table Initialization and Resizing -------------- */ + + /** + * Initializes table, using the size recorded in sizeCtl. + */ private final Node[] initTable() { Node[] tab; int sc; - while ((tab = table) == null) { + while ((tab = table) == null || tab.length == 0) { if ((sc = sizeCtl) < 0) Thread.yield(); // lost initialization race; just spin else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { try { - if ((tab = table) == null) { + if ((tab = table) == null || tab.length == 0) { int n = (sc > 0) ? sc : DEFAULT_CAPACITY; - table = tab = (Node[])new Node[n]; + @SuppressWarnings({"rawtypes","unchecked"}) + Node[] nt = (Node[])new Node[n]; + table = tab = nt; sc = n - (n >>> 2); } } finally { @@ -1921,10 +2212,10 @@ public class ConcurrentHashMap extends AbstractMap * @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; + CounterCell[] as; long b, s; if ((as = counterCells) != null || !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) { - Cell a; long v; int m; + CounterCell a; long v; int m; boolean uncontended = true; if (as == null || (m = as.length - 1) < 0 || (a = as[ThreadLocalRandom.getProbe() & m]) == null || @@ -1955,6 +2246,22 @@ public class ConcurrentHashMap extends AbstractMap } } + /** + * Helps transfer if a resize is in progress. + */ + final Node[] helpTransfer(Node[] tab, Node f) { + Node[] nextTab; int sc; + if ((f instanceof ForwardingNode) && + (nextTab = ((ForwardingNode)f).nextTable) != null) { + if (nextTab == nextTable && tab == table && + transferIndex > transferOrigin && (sc = sizeCtl) < -1 && + U.compareAndSwapInt(this, SIZECTL, sc, sc - 1)) + transfer(tab, nextTab); + return nextTab; + } + return table; + } + /** * Tries to presize table to accommodate the given number of elements. * @@ -1971,7 +2278,9 @@ public class ConcurrentHashMap extends AbstractMap if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { try { if (table == tab) { - table = (Node[])new Node[n]; + @SuppressWarnings({"rawtypes","unchecked"}) + Node[] nt = (Node[])new Node[n]; + table = nt; sc = n - (n >>> 2); } } finally { @@ -1997,7 +2306,9 @@ public class ConcurrentHashMap extends AbstractMap stride = MIN_TRANSFER_STRIDE; // subdivide range if (nextTab == null) { // initiating try { - nextTab = (Node[])new Node[n << 1]; + @SuppressWarnings({"rawtypes","unchecked"}) + Node[] nt = (Node[])new Node[n << 1]; + nextTab = nt; } catch (Throwable ex) { // try to cope with OOME sizeCtl = Integer.MAX_VALUE; return; @@ -2005,7 +2316,7 @@ public class ConcurrentHashMap extends AbstractMap nextTable = nextTab; transferOrigin = n; transferIndex = n; - Node rev = new Node(MOVED, tab, null, null); + ForwardingNode rev = new ForwardingNode(tab); for (int k = n; k > 0;) { // progressively reveal ready slots int nextk = (k > stride) ? k - stride : 0; for (int m = nextk; m < k; ++m) @@ -2016,12 +2327,13 @@ public class ConcurrentHashMap extends AbstractMap } } int nextn = nextTab.length; - Node fwd = new Node(MOVED, nextTab, null, null); + ForwardingNode fwd = new ForwardingNode(nextTab); boolean advance = true; + boolean finishing = false; // to ensure sweep before committing nextTab for (int i = 0, bound = 0;;) { - int nextIndex, nextBound; Node f; Object fk; + int nextIndex, nextBound, fh; Node f; while (advance) { - if (--i >= bound) + if (--i >= bound || finishing) advance = false; else if ((nextIndex = transferIndex) <= transferOrigin) { i = -1; @@ -2037,14 +2349,19 @@ public class ConcurrentHashMap extends AbstractMap } } if (i < 0 || i >= n || i + n >= nextn) { + if (finishing) { + nextTable = null; + table = nextTab; + sizeCtl = (n << 1) - (n >>> 1); + return; + } for (int sc;;) { if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, ++sc)) { - if (sc == -1) { - nextTable = null; - table = nextTab; - sizeCtl = (n << 1) - (n >>> 1); - } - return; + if (sc != -1) + return; + finishing = advance = true; + i = n; // recheck before commit + break; } } } @@ -2055,106 +2372,96 @@ public class ConcurrentHashMap extends AbstractMap advance = true; } } - else if (f.hash >= 0) { + else if ((fh = f.hash) == MOVED) + advance = true; // already processed + else { synchronized (f) { if (tabAt(tab, i) == f) { - int runBit = f.hash & n; - Node lastRun = f, lo = null, hi = null; - for (Node p = f.next; p != null; p = p.next) { - int b = p.hash & n; - if (b != runBit) { - runBit = b; - lastRun = p; + Node ln, hn; + if (fh >= 0) { + int runBit = fh & n; + Node lastRun = f; + for (Node p = f.next; p != null; p = p.next) { + int b = p.hash & n; + if (b != runBit) { + runBit = b; + lastRun = p; + } } - } - if (runBit == 0) - lo = lastRun; - else - hi = lastRun; - for (Node 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(ph, pk, pv, lo); - else - hi = new Node(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 t = (TreeBin)fk; - long stamp = t.writeLock(); - try { - if (tabAt(tab, i) == f) { - TreeNode root; - Node ln = null, hn = null; - if ((root = t.root) != null) { - Node e, p; TreeNode lr, rr; int lh; - TreeBin 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; + if (runBit == 0) { + ln = lastRun; + hn = null; } else { - lt = new TreeBin(); - ht = new TreeBin(); - 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(p.hash, p.key, - p.val, ln); - lt = null; + hn = lastRun; + ln = null; + } + for (Node p = f; p != lastRun; p = p.next) { + int ph = p.hash; K pk = p.key; V pv = p.val; + if ((ph & n) == 0) + ln = new Node(ph, pk, pv, ln); + else + hn = new Node(ph, pk, pv, hn); + } + setTabAt(nextTab, i, ln); + setTabAt(nextTab, i + n, hn); + setTabAt(tab, i, fwd); + advance = true; + } + else if (f instanceof TreeBin) { + TreeBin t = (TreeBin)f; + TreeNode lo = null, loTail = null; + TreeNode hi = null, hiTail = null; + int lc = 0, hc = 0; + for (Node e = t.first; e != null; e = e.next) { + int h = e.hash; + TreeNode p = new TreeNode + (h, e.key, e.val, null, null); + if ((h & n) == 0) { + if ((p.prev = loTail) == null) + lo = p; + else + loTail.next = p; + loTail = p; + ++lc; } - if (hc < TREE_THRESHOLD) { - for (p = ht.first; p != null; p = p.next) - hn = new Node(p.hash, p.key, - p.val, hn); - ht = null; + else { + if ((p.prev = hiTail) == null) + hi = p; + else + hiTail.next = p; + hiTail = p; + ++hc; } } - if (ln == null && lt != null) - ln = new Node(MOVED, lt, null, null); - if (hn == null && ht != null) - hn = new Node(MOVED, ht, null, null); + ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : + (hc != 0) ? new TreeBin(lo) : t; + hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : + (lc != 0) ? new TreeBin(hi) : t; + setTabAt(nextTab, i, ln); + setTabAt(nextTab, i + n, hn); + setTabAt(tab, i, fwd); + advance = true; } - 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 -------------- */ + /** + * A padded cell for distributing counts. Adapted from LongAdder + * and Striped64. See their internal docs for explanation. + */ + @sun.misc.Contended static final class CounterCell { + volatile long value; + CounterCell(long x) { value = x; } + } + final long sumCount() { - Cell[] as = counterCells; Cell a; + CounterCell[] as = counterCells; CounterCell a; long sum = baseCount; if (as != null) { for (int i = 0; i < as.length; ++i) { @@ -2175,16 +2482,16 @@ public class ConcurrentHashMap extends AbstractMap } boolean collide = false; // True if last slot nonempty for (;;) { - Cell[] as; Cell a; int n; long v; + CounterCell[] as; CounterCell a; int n; long v; if ((as = counterCells) != null && (n = as.length) > 0) { if ((a = as[(n - 1) & h]) == null) { if (cellsBusy == 0) { // Try to attach new Cell - Cell r = new Cell(x); // Optimistic create + CounterCell r = new CounterCell(x); // Optimistic create if (cellsBusy == 0 && U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { boolean created = false; try { // Recheck under lock - Cell[] rs; int m, j; + CounterCell[] rs; int m, j; if ((rs = counterCells) != null && (m = rs.length) > 0 && rs[j = (m - 1) & h] == null) { @@ -2213,7 +2520,7 @@ public class ConcurrentHashMap extends AbstractMap U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { try { if (counterCells == as) {// Expand table unless stale - Cell[] rs = new Cell[n << 1]; + CounterCell[] rs = new CounterCell[n << 1]; for (int i = 0; i < n; ++i) rs[i] = as[i]; counterCells = rs; @@ -2231,8 +2538,8 @@ public class ConcurrentHashMap extends AbstractMap boolean init = false; try { // Initialize table if (counterCells == as) { - Cell[] rs = new Cell[2]; - rs[h & 1] = new Cell(x); + CounterCell[] rs = new CounterCell[2]; + rs[h & 1] = new CounterCell(x); counterCells = rs; init = true; } @@ -2247,1068 +2554,953 @@ public class ConcurrentHashMap extends AbstractMap } } - /* ----------------Table Traversal -------------- */ + /* ---------------- Conversion from/to TreeBins -------------- */ /** - * 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. + * Replaces all linked nodes in bin at given index unless table is + * too small, in which case resizes instead. */ - static class Traverser { - Node[] tab; // current table; updated if resized - Node 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[] tab, int size, int index, int limit) { - this.tab = tab; - this.baseSize = size; - this.baseIndex = this.index = index; - this.baseLimit = limit; - this.next = null; - } - - /** - * Advances if possible, returning next valid node, or null if none. - */ - final Node advance() { - Node e; - if ((e = next) != null) - e = e.next; - for (;;) { - Node[] t; int i, n; 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)ek).first; - else { - tab = (Node[])ek; - e = null; - continue; + private final void treeifyBin(Node[] tab, int index) { + Node b; int n, sc; + if (tab != null) { + if ((n = tab.length) < MIN_TREEIFY_CAPACITY) { + if (tab == table && (sc = sizeCtl) >= 0 && + U.compareAndSwapInt(this, SIZECTL, sc, -2)) + transfer(tab, null); + } + else if ((b = tabAt(tab, index)) != null && b.hash >= 0) { + synchronized (b) { + if (tabAt(tab, index) == b) { + TreeNode hd = null, tl = null; + for (Node e = b; e != null; e = e.next) { + TreeNode p = + new TreeNode(e.hash, e.key, e.val, + null, null); + if ((p.prev = tl) == null) + hd = p; + else + tl.next = p; + tl = p; + } + setTabAt(tab, index, new TreeBin(hd)); } } - 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 + * Returns a list on non-TreeNodes replacing those in given list. */ - static class BaseIterator extends Traverser { - final ConcurrentHashMap map; - Node lastReturned; - BaseIterator(Node[] tab, int size, int index, int limit, - ConcurrentHashMap map) { - super(tab, size, index, limit); - this.map = map; - advance(); + static Node untreeify(Node b) { + Node hd = null, tl = null; + for (Node q = b; q != null; q = q.next) { + Node p = new Node(q.hash, q.key, q.val, null); + if (tl == null) + hd = p; + else + tl.next = p; + tl = p; } + return hd; + } - public final boolean hasNext() { return next != null; } - public final boolean hasMoreElements() { return next != null; } + /* ---------------- TreeNodes -------------- */ - public final void remove() { - Node p; - if ((p = lastReturned) == null) - throw new IllegalStateException(); - lastReturned = null; - map.internalReplace((K)p.key, null, null); - } - } + /** + * Nodes for use in TreeBins + */ + static final class TreeNode extends Node { + TreeNode parent; // red-black tree links + TreeNode left; + TreeNode right; + TreeNode prev; // needed to unlink next upon deletion + boolean red; - static final class KeyIterator extends BaseIterator - implements Iterator, Enumeration { - KeyIterator(Node[] tab, int index, int size, int limit, - ConcurrentHashMap map) { - super(tab, index, size, limit, map); + TreeNode(int hash, K key, V val, Node next, + TreeNode parent) { + super(hash, key, val, next); + this.parent = parent; } - public final K next() { - Node p; - if ((p = next) == null) - throw new NoSuchElementException(); - K k = (K)p.key; - lastReturned = p; - advance(); - return k; + Node find(int h, Object k) { + return findTreeNode(h, k, null); } - public final K nextElement() { return next(); } + /** + * Returns the TreeNode (or null if not found) for the given key + * starting at given root. + */ + final TreeNode findTreeNode(int h, Object k, Class kc) { + if (k != null) { + TreeNode p = this; + do { + int ph, dir; K pk; TreeNode q; + TreeNode pl = p.left, pr = p.right; + if ((ph = p.hash) > h) + p = pl; + else if (ph < h) + p = pr; + else if ((pk = p.key) == k || (pk != null && k.equals(pk))) + return p; + else if (pl == null && pr == null) + break; + else if ((kc != null || + (kc = comparableClassFor(k)) != null) && + (dir = compareComparables(kc, k, pk)) != 0) + p = (dir < 0) ? pl : pr; + else if (pl == null) + p = pr; + else if (pr == null || + (q = pr.findTreeNode(h, k, kc)) == null) + p = pl; + else + return q; + } while (p != null); + } + return null; + } } - static final class ValueIterator extends BaseIterator - implements Iterator, Enumeration { - ValueIterator(Node[] tab, int index, int size, int limit, - ConcurrentHashMap map) { - super(tab, index, size, limit, map); - } - - public final V next() { - Node p; - if ((p = next) == null) - throw new NoSuchElementException(); - V v = p.val; - lastReturned = p; - advance(); - return v; - } + /* ---------------- TreeBins -------------- */ - public final V nextElement() { return next(); } - } + /** + * TreeNodes used at the heads of bins. TreeBins do not hold user + * keys or values, but instead point to list of TreeNodes and + * their root. They also maintain a parasitic read-write lock + * forcing writers (who hold bin lock) to wait for readers (who do + * not) to complete before tree restructuring operations. + */ + static final class TreeBin extends Node { + TreeNode root; + volatile TreeNode first; + volatile Thread waiter; + volatile int lockState; + // values for lockState + static final int WRITER = 1; // set while holding write lock + static final int WAITER = 2; // set when waiting for write lock + static final int READER = 4; // increment value for setting read lock - static final class EntryIterator extends BaseIterator - implements Iterator> { - EntryIterator(Node[] tab, int index, int size, int limit, - ConcurrentHashMap map) { - super(tab, index, size, limit, map); + /** + * Creates bin with initial set of nodes headed by b. + */ + TreeBin(TreeNode b) { + super(TREEBIN, null, null, null); + this.first = b; + TreeNode r = null; + for (TreeNode x = b, next; x != null; x = next) { + next = (TreeNode)x.next; + x.left = x.right = null; + if (r == null) { + x.parent = null; + x.red = false; + r = x; + } + else { + Object key = x.key; + int hash = x.hash; + Class kc = null; + for (TreeNode p = r;;) { + int dir, ph; + if ((ph = p.hash) > hash) + dir = -1; + else if (ph < hash) + dir = 1; + else if ((kc != null || + (kc = comparableClassFor(key)) != null)) + dir = compareComparables(kc, key, p.key); + else + dir = 0; + TreeNode xp = p; + if ((p = (dir <= 0) ? p.left : p.right) == null) { + x.parent = xp; + if (dir <= 0) + xp.left = x; + else + xp.right = x; + r = balanceInsertion(r, x); + break; + } + } + } + } + this.root = r; } - public final Map.Entry next() { - Node 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, map); + /** + * Acquires write lock for tree restructuring. + */ + private final void lockRoot() { + if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER)) + contendedLock(); // offload to separate method } - } - static final class KeySpliterator extends Traverser - implements Spliterator { - long est; // size estimate - KeySpliterator(Node[] tab, int size, int index, int limit, - long est) { - super(tab, size, index, limit); - this.est = est; + /** + * Releases write lock for tree restructuring. + */ + private final void unlockRoot() { + lockState = 0; } - public Spliterator trySplit() { - int i, f, h; - return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : - new KeySpliterator(tab, baseSize, baseLimit = h, - f, est >>>= 1); + /** + * Possibly blocks awaiting root lock. + */ + private final void contendedLock() { + boolean waiting = false; + for (int s;;) { + if (((s = lockState) & WRITER) == 0) { + if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) { + if (waiting) + waiter = null; + return; + } + } + else if ((s | WAITER) == 0) { + if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) { + waiting = true; + waiter = Thread.currentThread(); + } + } + else if (waiting) + LockSupport.park(this); + } } - public void forEachRemaining(Consumer action) { - if (action == null) throw new NullPointerException(); - for (Node p; (p = advance()) != null;) - action.accept((K)p.key); + /** + * Returns matching node or null if none. Tries to search + * using tree comparisons from root, but continues linear + * search when lock not available. + */ + final Node find(int h, Object k) { + if (k != null) { + for (Node e = first; e != null; e = e.next) { + int s; K ek; + if (((s = lockState) & (WAITER|WRITER)) != 0) { + if (e.hash == h && + ((ek = e.key) == k || (ek != null && k.equals(ek)))) + return e; + } + else if (U.compareAndSwapInt(this, LOCKSTATE, s, + s + READER)) { + TreeNode r, p; + try { + p = ((r = root) == null ? null : + r.findTreeNode(h, k, null)); + } finally { + Thread w; + if (U.getAndAddInt(this, LOCKSTATE, -READER) == + (READER|WAITER) && (w = waiter) != null) + LockSupport.unpark(w); + } + return p; + } + } + } + return null; } - public boolean tryAdvance(Consumer action) { - if (action == null) throw new NullPointerException(); - Node p; - if ((p = advance()) == null) - return false; - action.accept((K)p.key); - return true; + /** + * Finds or adds a node. + * @return null if added + */ + final TreeNode putTreeVal(int h, K k, V v) { + Class kc = null; + for (TreeNode p = root;;) { + int dir, ph; K pk; TreeNode q, pr; + if (p == null) { + first = root = new TreeNode(h, k, v, null, null); + break; + } + else if ((ph = p.hash) > h) + dir = -1; + else if (ph < h) + dir = 1; + else if ((pk = p.key) == k || (pk != null && k.equals(pk))) + return p; + else if ((kc == null && + (kc = comparableClassFor(k)) == null) || + (dir = compareComparables(kc, k, pk)) == 0) { + if (p.left == null) + dir = 1; + else if ((pr = p.right) == null || + (q = pr.findTreeNode(h, k, kc)) == null) + dir = -1; + else + return q; + } + TreeNode xp = p; + if ((p = (dir < 0) ? p.left : p.right) == null) { + TreeNode x, f = first; + first = x = new TreeNode(h, k, v, f, xp); + if (f != null) + f.prev = x; + if (dir < 0) + xp.left = x; + else + xp.right = x; + if (!xp.red) + x.red = true; + else { + lockRoot(); + try { + root = balanceInsertion(root, x); + } finally { + unlockRoot(); + } + } + break; + } + } + assert checkInvariants(root); + return null; } - public long estimateSize() { return est; } + /** + * Removes the given node, that must be present before this + * call. This is messier than typical red-black deletion code + * because we cannot swap the contents of an interior node + * with a leaf successor that is pinned by "next" pointers + * that are accessible independently of lock. So instead we + * swap the tree linkages. + * + * @return true if now too small, so should be untreeified + */ + final boolean removeTreeNode(TreeNode p) { + TreeNode next = (TreeNode)p.next; + TreeNode pred = p.prev; // unlink traversal pointers + TreeNode r, rl; + if (pred == null) + first = next; + else + pred.next = next; + if (next != null) + next.prev = pred; + if (first == null) { + root = null; + return true; + } + if ((r = root) == null || r.right == null || // too small + (rl = r.left) == null || rl.left == null) + return true; + lockRoot(); + try { + TreeNode replacement; + TreeNode pl = p.left; + TreeNode pr = p.right; + if (pl != null && pr != null) { + TreeNode s = pr, sl; + while ((sl = s.left) != null) // find successor + s = sl; + boolean c = s.red; s.red = p.red; p.red = c; // swap colors + TreeNode sr = s.right; + TreeNode pp = p.parent; + if (s == pr) { // p was s's direct parent + p.parent = s; + s.right = p; + } + else { + TreeNode sp = s.parent; + if ((p.parent = sp) != null) { + if (s == sp.left) + sp.left = p; + else + sp.right = p; + } + if ((s.right = pr) != null) + pr.parent = s; + } + p.left = null; + if ((p.right = sr) != null) + sr.parent = p; + if ((s.left = pl) != null) + pl.parent = s; + if ((s.parent = pp) == null) + r = s; + else if (p == pp.left) + pp.left = s; + else + pp.right = s; + if (sr != null) + replacement = sr; + else + replacement = p; + } + else if (pl != null) + replacement = pl; + else if (pr != null) + replacement = pr; + else + replacement = p; + if (replacement != p) { + TreeNode pp = replacement.parent = p.parent; + if (pp == null) + r = replacement; + else if (p == pp.left) + pp.left = replacement; + else + pp.right = replacement; + p.left = p.right = p.parent = null; + } - public int characteristics() { - return Spliterator.DISTINCT | Spliterator.CONCURRENT | - Spliterator.NONNULL; - } - } + root = (p.red) ? r : balanceDeletion(r, replacement); - static final class ValueSpliterator extends Traverser - implements Spliterator { - long est; // size estimate - ValueSpliterator(Node[] tab, int size, int index, int limit, - long est) { - super(tab, size, index, limit); - this.est = est; + if (p == replacement) { // detach pointers + TreeNode pp; + if ((pp = p.parent) != null) { + if (p == pp.left) + pp.left = null; + else if (p == pp.right) + pp.right = null; + p.parent = null; + } + } + } finally { + unlockRoot(); + } + assert checkInvariants(root); + return false; } - public Spliterator trySplit() { - int i, f, h; - return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : - new ValueSpliterator(tab, baseSize, baseLimit = h, - f, est >>>= 1); - } + /* ------------------------------------------------------------ */ + // Red-black tree methods, all adapted from CLR - public void forEachRemaining(Consumer action) { - if (action == null) throw new NullPointerException(); - for (Node p; (p = advance()) != null;) - action.accept(p.val); + static TreeNode rotateLeft(TreeNode root, + TreeNode p) { + TreeNode r, pp, rl; + if (p != null && (r = p.right) != null) { + if ((rl = p.right = r.left) != null) + rl.parent = p; + if ((pp = r.parent = p.parent) == null) + (root = r).red = false; + else if (pp.left == p) + pp.left = r; + else + pp.right = r; + r.left = p; + p.parent = r; + } + return root; } - public boolean tryAdvance(Consumer action) { - if (action == null) throw new NullPointerException(); - Node p; - if ((p = advance()) == null) - return false; - action.accept(p.val); - return true; + static TreeNode rotateRight(TreeNode root, + TreeNode p) { + TreeNode l, pp, lr; + if (p != null && (l = p.left) != null) { + if ((lr = p.left = l.right) != null) + lr.parent = p; + if ((pp = l.parent = p.parent) == null) + (root = l).red = false; + else if (pp.right == p) + pp.right = l; + else + pp.left = l; + l.right = p; + p.parent = l; + } + return root; } - public long estimateSize() { return est; } - - public int characteristics() { - return Spliterator.CONCURRENT | Spliterator.NONNULL; + static TreeNode balanceInsertion(TreeNode root, + TreeNode x) { + x.red = true; + for (TreeNode xp, xpp, xppl, xppr;;) { + if ((xp = x.parent) == null) { + x.red = false; + return x; + } + else if (!xp.red || (xpp = xp.parent) == null) + return root; + if (xp == (xppl = xpp.left)) { + if ((xppr = xpp.right) != null && xppr.red) { + xppr.red = false; + xp.red = false; + xpp.red = true; + x = xpp; + } + else { + if (x == xp.right) { + root = rotateLeft(root, x = xp); + xpp = (xp = x.parent) == null ? null : xp.parent; + } + if (xp != null) { + xp.red = false; + if (xpp != null) { + xpp.red = true; + root = rotateRight(root, xpp); + } + } + } + } + else { + if (xppl != null && xppl.red) { + xppl.red = false; + xp.red = false; + xpp.red = true; + x = xpp; + } + else { + if (x == xp.left) { + root = rotateRight(root, x = xp); + xpp = (xp = x.parent) == null ? null : xp.parent; + } + if (xp != null) { + xp.red = false; + if (xpp != null) { + xpp.red = true; + root = rotateLeft(root, xpp); + } + } + } + } + } } - } - static final class EntrySpliterator extends Traverser - implements Spliterator> { - final ConcurrentHashMap map; // To export MapEntry - long est; // size estimate - EntrySpliterator(Node[] tab, int size, int index, int limit, - long est, ConcurrentHashMap map) { - super(tab, size, index, limit); - this.map = map; - this.est = est; + static TreeNode balanceDeletion(TreeNode root, + TreeNode x) { + for (TreeNode xp, xpl, xpr;;) { + if (x == null || x == root) + return root; + else if ((xp = x.parent) == null) { + x.red = false; + return x; + } + else if (x.red) { + x.red = false; + return root; + } + else if ((xpl = xp.left) == x) { + if ((xpr = xp.right) != null && xpr.red) { + xpr.red = false; + xp.red = true; + root = rotateLeft(root, xp); + xpr = (xp = x.parent) == null ? null : xp.right; + } + if (xpr == null) + x = xp; + else { + TreeNode sl = xpr.left, sr = xpr.right; + if ((sr == null || !sr.red) && + (sl == null || !sl.red)) { + xpr.red = true; + x = xp; + } + else { + if (sr == null || !sr.red) { + if (sl != null) + sl.red = false; + xpr.red = true; + root = rotateRight(root, xpr); + xpr = (xp = x.parent) == null ? + null : xp.right; + } + if (xpr != null) { + xpr.red = (xp == null) ? false : xp.red; + if ((sr = xpr.right) != null) + sr.red = false; + } + if (xp != null) { + xp.red = false; + root = rotateLeft(root, xp); + } + x = root; + } + } + } + else { // symmetric + if (xpl != null && xpl.red) { + xpl.red = false; + xp.red = true; + root = rotateRight(root, xp); + xpl = (xp = x.parent) == null ? null : xp.left; + } + if (xpl == null) + x = xp; + else { + TreeNode sl = xpl.left, sr = xpl.right; + if ((sl == null || !sl.red) && + (sr == null || !sr.red)) { + xpl.red = true; + x = xp; + } + else { + if (sl == null || !sl.red) { + if (sr != null) + sr.red = false; + xpl.red = true; + root = rotateLeft(root, xpl); + xpl = (xp = x.parent) == null ? + null : xp.left; + } + if (xpl != null) { + xpl.red = (xp == null) ? false : xp.red; + if ((sl = xpl.left) != null) + sl.red = false; + } + if (xp != null) { + xp.red = false; + root = rotateRight(root, xp); + } + x = root; + } + } + } + } } - public Spliterator> trySplit() { - int i, f, h; - return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : - new EntrySpliterator(tab, baseSize, baseLimit = h, - f, est >>>= 1, map); - } - - public void forEachRemaining(Consumer> action) { - if (action == null) throw new NullPointerException(); - for (Node p; (p = advance()) != null; ) - action.accept(new MapEntry((K)p.key, p.val, map)); - } - - public boolean tryAdvance(Consumer> action) { - if (action == null) throw new NullPointerException(); - Node p; - if ((p = advance()) == null) + /** + * Recursive invariant check + */ + static boolean checkInvariants(TreeNode t) { + TreeNode tp = t.parent, tl = t.left, tr = t.right, + tb = t.prev, tn = (TreeNode)t.next; + if (tb != null && tb.next != t) + return false; + if (tn != null && tn.prev != t) + return false; + if (tp != null && t != tp.left && t != tp.right) + return false; + if (tl != null && (tl.parent != t || tl.hash > t.hash)) + return false; + if (tr != null && (tr.parent != t || tr.hash < t.hash)) + return false; + if (t.red && tl != null && tl.red && tr != null && tr.red) + return false; + if (tl != null && !checkInvariants(tl)) + return false; + if (tr != null && !checkInvariants(tr)) return false; - action.accept(new MapEntry((K)p.key, p.val, map)); return true; } - public long estimateSize() { return est; } - - public int characteristics() { - return Spliterator.DISTINCT | Spliterator.CONCURRENT | - Spliterator.NONNULL; + private static final sun.misc.Unsafe U; + private static final long LOCKSTATE; + static { + try { + U = sun.misc.Unsafe.getUnsafe(); + Class k = TreeBin.class; + LOCKSTATE = U.objectFieldOffset + (k.getDeclaredField("lockState")); + } catch (Exception e) { + throw new Error(e); + } } } - - /* ---------------- Public operations -------------- */ - - /** - * Creates a new, empty map with the default initial table size (16). - */ - public ConcurrentHashMap() { - } + /* ----------------Table Traversal -------------- */ /** - * Creates a new, empty map with an initial table size - * accommodating the specified number of elements without the need - * to dynamically resize. + * Encapsulates traversal for methods such as containsValue; also + * serves as a base class for other iterators and spliterators. * - * @param initialCapacity The implementation performs internal - * sizing to accommodate this many elements. - * @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. + * 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. * - * @param m the map + * 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. */ - public ConcurrentHashMap(Map m) { - this.sizeCtl = DEFAULT_CAPACITY; - internalPutAll(m); - } + static class Traverser { + Node[] tab; // current table; updated if resized + Node 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 - /** - * 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, 1); - } + Traverser(Node[] tab, int size, int index, int limit) { + this.tab = tab; + this.baseSize = size; + this.baseIndex = this.index = index; + this.baseLimit = limit; + this.next = null; + } - /** - * 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, - * 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; + /** + * Advances if possible, returning next valid node, or null if none. + */ + final Node advance() { + Node e; + if ((e = next) != null) + e = e.next; + for (;;) { + Node[] t; int i, n; K 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 (e instanceof ForwardingNode) { + tab = ((ForwardingNode)e).nextTable; + e = null; + continue; + } + else if (e instanceof TreeBin) + e = ((TreeBin)e).first; + else + e = null; + } + if ((index += baseSize) >= n) + index = ++baseIndex; // visit upper slots if present + } + } } /** - * Creates a new {@link Set} backed by a ConcurrentHashMap - * from the given type to {@code Boolean.TRUE}. - * - * @return the new set - * @since 1.8 + * Base of key, value, and entry Iterators. Adds fields to + * Traverser to support iterator.remove. */ - public static KeySetView newKeySet() { - return new KeySetView - (new ConcurrentHashMap(), Boolean.TRUE); - } + static class BaseIterator extends Traverser { + final ConcurrentHashMap map; + Node lastReturned; + BaseIterator(Node[] tab, int size, int index, int limit, + ConcurrentHashMap map) { + super(tab, size, index, limit); + this.map = map; + advance(); + } - /** - * 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 - * @return the new set - * @since 1.8 - */ - public static KeySetView newKeySet(int initialCapacity) { - return new KeySetView - (new ConcurrentHashMap(initialCapacity), Boolean.TRUE); - } + public final boolean hasNext() { return next != null; } + public final boolean hasMoreElements() { return next != null; } - /** - * Returns {@code true} if this map contains no key-value mappings. - * - * @return {@code true} if this map contains no key-value mappings - */ - public boolean isEmpty() { - return sumCount() <= 0L; // ignore transient negative values + public final void remove() { + Node p; + if ((p = lastReturned) == null) + throw new IllegalStateException(); + lastReturned = null; + map.replaceNode(p.key, null, null); + } } - /** - * Returns the number of key-value mappings in this map. If the - * map contains more than {@code Integer.MAX_VALUE} elements, returns - * {@code Integer.MAX_VALUE}. - * - * @return the number of key-value mappings in this map - */ - public int size() { - long n = sumCount(); - return ((n < 0L) ? 0 : - (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE : - (int)n); + static final class KeyIterator extends BaseIterator + implements Iterator, Enumeration { + KeyIterator(Node[] tab, int index, int size, int limit, + ConcurrentHashMap map) { + super(tab, index, size, limit, map); + } + + public final K next() { + Node p; + if ((p = next) == null) + throw new NoSuchElementException(); + K k = p.key; + lastReturned = p; + advance(); + return k; + } + + public final K nextElement() { return next(); } } - /** - * 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 - } - - /** - * Returns the value to which the specified key is mapped, - * or {@code null} if this map contains no mapping for the key. - * - *

      More formally, if this map contains a mapping from a key - * {@code k} to a value {@code v} such that {@code key.equals(k)}, - * then this method returns {@code v}; otherwise it returns - * {@code null}. (There can be at most one such mapping.) - * - * @throws NullPointerException if the specified key is null - */ - public V get(Object key) { - 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; - } - - /** - * Tests if the specified object is a key in this table. - * - * @param key possible key - * @return {@code true} if and only if the specified object - * is a key in this table, as determined by the - * {@code equals} method; {@code false} otherwise - * @throws NullPointerException if the specified key is null - */ - public boolean containsKey(Object key) { - return internalGet(key) != null; - } - - /** - * Returns {@code true} if this map maps one or more keys to the - * 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 - * specified value - * @throws NullPointerException if the specified value is null - */ - public boolean containsValue(Object value) { - if (value == null) - throw new NullPointerException(); - Node[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node p; (p = it.advance()) != null; ) { - V v; - if ((v = p.val) == value || value.equals(v)) - return true; - } + static final class ValueIterator extends BaseIterator + implements Iterator, Enumeration { + ValueIterator(Node[] tab, int index, int size, int limit, + ConcurrentHashMap map) { + super(tab, index, size, limit, map); } - return false; - } - - /** - * Legacy method testing if some key maps into the specified value - * in this table. This method is identical in functionality to - * {@link #containsValue(Object)}, and exists solely to ensure - * full compatibility with class {@link java.util.Hashtable}, - * which supported this method prior to introduction of the - * Java Collections framework. - * - * @param value a value to search for - * @return {@code true} if and only if some key maps to the - * {@code value} argument in this table as - * determined by the {@code equals} method; - * {@code false} otherwise - * @throws NullPointerException if the specified value is null - */ - public boolean contains(Object value) { - return containsValue(value); - } - - /** - * Maps the specified key to the specified value in this table. - * Neither the key nor the value can be null. - * - *

      The value can be retrieved by calling the {@code get} method - * with a key that is equal to the original key. - * - * @param key key with which the specified value is to be associated - * @param value value to be associated with the specified key - * @return the previous value associated with {@code key}, or - * {@code null} if there was no mapping for {@code key} - * @throws NullPointerException if the specified key or value is null - */ - public V put(K key, V value) { - return internalPut(key, value, false); - } - - /** - * {@inheritDoc} - * - * @return the previous value associated with the specified key, - * or {@code null} if there was no mapping for the key - * @throws NullPointerException if the specified key or value is null - */ - public V putIfAbsent(K key, V value) { - return internalPut(key, value, true); - } - - /** - * Copies all of the mappings from the specified map to this one. - * These mappings replace any mappings that this map had for any of the - * keys currently in the specified map. - * - * @param m mappings to be stored in this map - */ - public void putAll(Map m) { - 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 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 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 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 remappingFunction) { - return internalMerge(key, value, remappingFunction); - } - - /** - * Removes the key (and its corresponding value) from this map. - * This method does nothing if the key is not in the map. - * - * @param key the key that needs to be removed - * @return the previous value associated with {@code key}, or - * {@code null} if there was no mapping for {@code key} - * @throws NullPointerException if the specified key is null - */ - public V remove(Object key) { - return internalReplace(key, null, null); - } - - /** - * {@inheritDoc} - * - * @throws NullPointerException if the specified key is null - */ - public boolean remove(Object key, Object value) { - if (key == null) - throw new NullPointerException(); - return value != null && internalReplace(key, null, value) != null; - } - - /** - * {@inheritDoc} - * - * @throws NullPointerException if any of the arguments are null - */ - public boolean replace(K key, V oldValue, V newValue) { - if (key == null || oldValue == null || newValue == null) - throw new NullPointerException(); - return internalReplace(key, newValue, oldValue) != null; - } - - /** - * {@inheritDoc} - * - * @return the previous value associated with the specified key, - * or {@code null} if there was no mapping for the key - * @throws NullPointerException if the specified key or value is null - */ - public V replace(K key, V value) { - if (key == null || value == null) - throw new NullPointerException(); - return internalReplace(key, value, null); - } - - /** - * Removes all of the mappings from this map. - */ - public void clear() { - internalClear(); - } + public final V next() { + Node p; + if ((p = next) == null) + throw new NoSuchElementException(); + V v = p.val; + lastReturned = p; + advance(); + return v; + } - /** - * Returns a {@link Set} view of the keys contained in this map. - * The set is backed by the map, so changes to the map are - * reflected in the set, and vice-versa. The set supports element - * removal, which removes the corresponding mapping from this 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. - * - *

      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 KeySetView keySet() { - KeySetView ks = keySet; - return (ks != null) ? ks : (keySet = new KeySetView(this, null)); + public final V nextElement() { return next(); } } - /** - * 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 keySet(V mappedValue) { - if (mappedValue == null) - throw new NullPointerException(); - return new KeySetView(this, mappedValue); - } + static final class EntryIterator extends BaseIterator + implements Iterator> { + EntryIterator(Node[] tab, int index, int size, int limit, + ConcurrentHashMap map) { + super(tab, index, size, limit, map); + } - /** - * Returns a {@link Collection} view of the values contained in this map. - * The collection is backed by the map, so changes to the map are - * reflected in the collection, and vice-versa. The collection - * supports element removal, which removes the corresponding - * mapping from this map, via the {@code Iterator.remove}, - * {@code Collection.remove}, {@code removeAll}, - * {@code retainAll}, and {@code clear} operations. It does not - * support the {@code add} or {@code addAll} operations. - * - *

      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 collection view - */ - public Collection values() { - ValuesView vs = values; - return (vs != null) ? vs : (values = new ValuesView(this)); + public final Map.Entry next() { + Node p; + if ((p = next) == null) + throw new NoSuchElementException(); + K k = p.key; + V v = p.val; + lastReturned = p; + advance(); + return new MapEntry(k, v, map); + } } /** - * Returns a {@link Set} view of the mappings contained in this map. - * The set is backed by the map, so changes to the map are - * reflected in the set, and vice-versa. The set supports element - * 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. - * - *

      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 + * Exported Entry for EntryIterator */ - public Set> entrySet() { - EntrySetView es = entrySet; - return (es != null) ? es : (entrySet = new EntrySetView(this)); - } + static final class MapEntry implements Map.Entry { + final K key; // non-null + V val; // non-null + final ConcurrentHashMap map; + MapEntry(K key, V val, ConcurrentHashMap map) { + this.key = key; + this.val = val; + this.map = map; + } + public K getKey() { return key; } + public V getValue() { return val; } + public int hashCode() { return key.hashCode() ^ val.hashCode(); } + public String toString() { return key + "=" + val; } - /** - * Returns an enumeration of the keys in this table. - * - * @return an enumeration of the keys in this table - * @see #keySet() - */ - public Enumeration keys() { - Node[] t; - int f = (t = table) == null ? 0 : t.length; - return new KeyIterator(t, f, 0, f, this); - } + 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))); + } - /** - * Returns an enumeration of the values in this table. - * - * @return an enumeration of the values in this table - * @see #values() - */ - public Enumeration elements() { - Node[] t; - int f = (t = table) == null ? 0 : t.length; - return new ValueIterator(t, f, 0, f, this); + /** + * Sets our entry's value and writes through to the map. The + * value to return is somewhat arbitrary here. Since we do not + * necessarily track asynchronous changes, the most recent + * "previous" value could be different from what we return (or + * could even have been removed, in which case the put will + * re-establish). We do not and cannot guarantee more. + */ + public V setValue(V value) { + if (value == null) throw new NullPointerException(); + V v = val; + val = value; + map.put(key, value); + return v; + } } - /** - * 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[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node p; (p = it.advance()) != null; ) - h += p.key.hashCode() ^ p.val.hashCode(); + static final class KeySpliterator extends Traverser + implements Spliterator { + long est; // size estimate + KeySpliterator(Node[] tab, int size, int index, int limit, + long est) { + super(tab, size, index, limit); + this.est = est; } - 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[] t; - int f = (t = table) == null ? 0 : t.length; - Traverser it = new Traverser(t, f, 0, f); - StringBuilder sb = new StringBuilder(); - sb.append('{'); - Node p; - if ((p = it.advance()) != null) { - for (;;) { - K k = (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(' '); - } + public Spliterator trySplit() { + int i, f, h; + return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : + new KeySpliterator(tab, baseSize, baseLimit = h, + f, est >>>= 1); } - 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)) + public void forEachRemaining(Consumer action) { + if (action == null) throw new NullPointerException(); + for (Node p; (p = advance()) != null;) + action.accept(p.key); + } + + public boolean tryAdvance(Consumer action) { + if (action == null) throw new NullPointerException(); + Node p; + if ((p = advance()) == null) return false; - Map m = (Map) o; - Node[] t; - int f = (t = table) == null ? 0 : t.length; - Traverser it = new Traverser(t, f, 0, f); - for (Node p; (p = it.advance()) != null; ) { - V val = p.val; - Object v = m.get(p.key); - if (v == null || (v != val && !v.equals(val))) - return false; - } - for (Map.Entry e : m.entrySet()) { - Object mk, mv, v; - if ((mk = e.getKey()) == null || - (mv = e.getValue()) == null || - (v = internalGet(mk)) == null || - (mv != v && !mv.equals(v))) - return false; - } + action.accept(p.key); + return true; } - return true; - } - /* ---------------- Serialization Support -------------- */ + public long estimateSize() { return est; } - /** - * Stripped-down version of helper class used in previous version, - * declared for the sake of serialization compatibility - */ - static class Segment extends ReentrantLock implements Serializable { - private static final long serialVersionUID = 2249069246763182397L; - final float loadFactor; - Segment(float lf) { this.loadFactor = lf; } + public int characteristics() { + return Spliterator.DISTINCT | Spliterator.CONCURRENT | + Spliterator.NONNULL; + } } - /** - * Saves the state of the {@code ConcurrentHashMap} instance to a - * stream (i.e., serializes it). - * @param s the stream - * @serialData - * the key (Object) and value (Object) - * for each key-value mapping, followed by a null pair. - * The key-value mappings are emitted in no particular order. - */ - private void writeObject(java.io.ObjectOutputStream s) - throws java.io.IOException { - // For serialization compatibility - // Emulate segment calculation from previous version of this class - int sshift = 0; - int ssize = 1; - while (ssize < DEFAULT_CONCURRENCY_LEVEL) { - ++sshift; - ssize <<= 1; + static final class ValueSpliterator extends Traverser + implements Spliterator { + long est; // size estimate + ValueSpliterator(Node[] tab, int size, int index, int limit, + long est) { + super(tab, size, index, limit); + this.est = est; } - int segmentShift = 32 - sshift; - int segmentMask = ssize - 1; - Segment[] segments = (Segment[]) - new Segment[DEFAULT_CONCURRENCY_LEVEL]; - for (int i = 0; i < segments.length; ++i) - segments[i] = new Segment(LOAD_FACTOR); - s.putFields().put("segments", segments); - s.putFields().put("segmentShift", segmentShift); - s.putFields().put("segmentMask", segmentMask); - s.writeFields(); - Node[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node p; (p = it.advance()) != null; ) { - s.writeObject(p.key); - s.writeObject(p.val); - } + public Spliterator trySplit() { + int i, f, h; + return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : + new ValueSpliterator(tab, baseSize, baseLimit = h, + f, est >>>= 1); } - s.writeObject(null); - s.writeObject(null); - segments = null; // throw away - } - /** - * Reconstitutes the instance from a stream (that is, deserializes it). - * @param s the stream - */ - private void readObject(java.io.ObjectInputStream s) - throws java.io.IOException, ClassNotFoundException { - s.defaultReadObject(); + public void forEachRemaining(Consumer action) { + if (action == null) throw new NullPointerException(); + for (Node p; (p = advance()) != null;) + action.accept(p.val); + } - // Create all nodes, then place in table once size is known - long size = 0L; - Node 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(h, k, v, p); - ++size; - } - else - break; + public boolean tryAdvance(Consumer action) { + if (action == null) throw new NullPointerException(); + Node p; + if ((p = advance()) == null) + return false; + action.accept(p.val); + return true; } - 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[] tab = (Node[])new Node[n]; - int mask = n - 1; - while (p != null) { - int j = p.hash & mask; - Node next = p.next; - Node 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[] tab = table; - for (int i = 0; i < tab.length; ++i) { - int c = 0; - for (Node 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; - } - } + + public long estimateSize() { return est; } + + public int characteristics() { + return Spliterator.CONCURRENT | Spliterator.NONNULL; } } - // ------------------------------------------------------- + static final class EntrySpliterator extends Traverser + implements Spliterator> { + final ConcurrentHashMap map; // To export MapEntry + long est; // size estimate + EntrySpliterator(Node[] tab, int size, int index, int limit, + long est, ConcurrentHashMap map) { + super(tab, size, index, limit); + this.map = map; + this.est = est; + } - // Overrides of other default Map methods + public Spliterator> trySplit() { + int i, f, h; + return (h = ((i = baseIndex) + (f = baseLimit)) >>> 1) <= i ? null : + new EntrySpliterator(tab, baseSize, baseLimit = h, + f, est >>>= 1, map); + } - public void forEach(BiConsumer action) { - if (action == null) throw new NullPointerException(); - Node[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node p; (p = it.advance()) != null; ) { - action.accept((K)p.key, p.val); - } + public void forEachRemaining(Consumer> action) { + if (action == null) throw new NullPointerException(); + for (Node p; (p = advance()) != null; ) + action.accept(new MapEntry(p.key, p.val, map)); } - } - public void replaceAll(BiFunction function) { - if (function == null) throw new NullPointerException(); - Node[] t; - if ((t = table) != null) { - Traverser it = new Traverser(t, t.length, 0, t.length); - for (Node p; (p = it.advance()) != null; ) { - K k = (K)p.key; - internalPut(k, function.apply(k, p.val), false); - } + public boolean tryAdvance(Consumer> action) { + if (action == null) throw new NullPointerException(); + Node p; + if ((p = advance()) == null) + return false; + action.accept(new MapEntry(p.key, p.val, map)); + return true; } - } - // ------------------------------------------------------- + public long estimateSize() { return est; } + + public int characteristics() { + return Spliterator.DISTINCT | Spliterator.CONCURRENT | + Spliterator.NONNULL; + } + } // Parallel bulk operations @@ -3429,10 +3621,10 @@ public class ConcurrentHashMap extends AbstractMap * of all (key, value) pairs * @since 1.8 */ - public double reduceToDoubleIn(long parallelismThreshold, - ToDoubleBiFunction transformer, - double basis, - DoubleBinaryOperator reducer) { + public double reduceToDouble(long parallelismThreshold, + ToDoubleBiFunction transformer, + double basis, + DoubleBinaryOperator reducer) { if (transformer == null || reducer == null) throw new NullPointerException(); return new MapReduceMappingsToDoubleTask @@ -4104,6 +4296,7 @@ public class ConcurrentHashMap extends AbstractMap return (i == n) ? r : Arrays.copyOf(r, i); } + @SuppressWarnings("unchecked") public final T[] toArray(T[] a) { long sz = map.mappingCount(); if (sz > MAX_ARRAY_SIZE) @@ -4202,6 +4395,7 @@ public class ConcurrentHashMap extends AbstractMap * {@link #keySet(Object) keySet(V)}, * {@link #newKeySet() newKeySet()}, * {@link #newKeySet(int) newKeySet(int)}. + * * @since 1.8 */ public static class KeySetView extends CollectionView @@ -4263,7 +4457,7 @@ public class ConcurrentHashMap extends AbstractMap V v; if ((v = value) == null) throw new UnsupportedOperationException(); - return map.internalPut(e, v, true) == null; + return map.putVal(e, v, true) == null; } /** @@ -4283,7 +4477,7 @@ public class ConcurrentHashMap extends AbstractMap if ((v = value) == null) throw new UnsupportedOperationException(); for (K e : c) { - if (map.internalPut(e, v, true) == null) + if (map.putVal(e, v, true) == null) added = true; } return added; @@ -4317,7 +4511,7 @@ public class ConcurrentHashMap extends AbstractMap if ((t = map.table) != null) { Traverser it = new Traverser(t, t.length, 0, t.length); for (Node p; (p = it.advance()) != null; ) - action.accept((K)p.key); + action.accept(p.key); } } } @@ -4418,7 +4612,7 @@ public class ConcurrentHashMap extends AbstractMap } public boolean add(Entry e) { - return map.internalPut(e.getKey(), e.getValue(), false) == null; + return map.putVal(e.getKey(), e.getValue(), false) == null; } public boolean addAll(Collection> c) { @@ -4463,7 +4657,7 @@ public class ConcurrentHashMap extends AbstractMap if ((t = map.table) != null) { Traverser it = new Traverser(t, t.length, 0, t.length); for (Node p; (p = it.advance()) != null; ) - action.accept(new MapEntry((K)p.key, p.val, map)); + action.accept(new MapEntry(p.key, p.val, map)); } } @@ -4506,23 +4700,25 @@ public class ConcurrentHashMap extends AbstractMap if ((e = next) != null) e = e.next; for (;;) { - Node[] t; int i, n; Object ek; + Node[] t; int i, n; K 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)ek).first; - else { - tab = (Node[])ek; + if (e instanceof ForwardingNode) { + tab = ((ForwardingNode)e).nextTable; e = null; continue; } + else if (e instanceof TreeBin) + e = ((TreeBin)e).first; + else + e = null; } if ((index += baseSize) >= n) - index = ++baseIndex; + index = ++baseIndex; // visit upper slots if present } } } @@ -4534,7 +4730,7 @@ public class ConcurrentHashMap extends AbstractMap * that we've already null-checked task arguments, so we force * simplest hoisted bypass to help avoid convoluted traps. */ - + @SuppressWarnings("serial") static final class ForEachKeyTask extends BulkTask { final Consumer action; @@ -4555,12 +4751,13 @@ public class ConcurrentHashMap extends AbstractMap action).fork(); } for (Node p; (p = advance()) != null;) - action.accept((K)p.key); + action.accept(p.key); propagateCompletion(); } } } + @SuppressWarnings("serial") static final class ForEachValueTask extends BulkTask { final Consumer action; @@ -4587,6 +4784,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachEntryTask extends BulkTask { final Consumer> action; @@ -4613,6 +4811,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachMappingTask extends BulkTask { final BiConsumer action; @@ -4633,12 +4832,13 @@ public class ConcurrentHashMap extends AbstractMap action).fork(); } for (Node p; (p = advance()) != null; ) - action.accept((K)p.key, p.val); + action.accept(p.key, p.val); propagateCompletion(); } } } + @SuppressWarnings("serial") static final class ForEachTransformedKeyTask extends BulkTask { final Function transformer; @@ -4663,7 +4863,7 @@ public class ConcurrentHashMap extends AbstractMap } for (Node p; (p = advance()) != null; ) { U u; - if ((u = transformer.apply((K)p.key)) != null) + if ((u = transformer.apply(p.key)) != null) action.accept(u); } propagateCompletion(); @@ -4671,6 +4871,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachTransformedValueTask extends BulkTask { final Function transformer; @@ -4703,6 +4904,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachTransformedEntryTask extends BulkTask { final Function, ? extends U> transformer; @@ -4735,6 +4937,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ForEachTransformedMappingTask extends BulkTask { final BiFunction transformer; @@ -4760,7 +4963,7 @@ public class ConcurrentHashMap extends AbstractMap } for (Node p; (p = advance()) != null; ) { U u; - if ((u = transformer.apply((K)p.key, p.val)) != null) + if ((u = transformer.apply(p.key, p.val)) != null) action.accept(u); } propagateCompletion(); @@ -4768,6 +4971,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class SearchKeysTask extends BulkTask { final Function searchFunction; @@ -4801,7 +5005,7 @@ public class ConcurrentHashMap extends AbstractMap propagateCompletion(); break; } - if ((u = searchFunction.apply((K)p.key)) != null) { + if ((u = searchFunction.apply(p.key)) != null) { if (result.compareAndSet(null, u)) quietlyCompleteRoot(); break; @@ -4811,6 +5015,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class SearchValuesTask extends BulkTask { final Function searchFunction; @@ -4854,6 +5059,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class SearchEntriesTask extends BulkTask { final Function, ? extends U> searchFunction; @@ -4897,6 +5103,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class SearchMappingsTask extends BulkTask { final BiFunction searchFunction; @@ -4930,7 +5137,7 @@ public class ConcurrentHashMap extends AbstractMap propagateCompletion(); break; } - if ((u = searchFunction.apply((K)p.key, p.val)) != null) { + if ((u = searchFunction.apply(p.key, p.val)) != null) { if (result.compareAndSet(null, u)) quietlyCompleteRoot(); break; @@ -4940,6 +5147,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ReduceKeysTask extends BulkTask { final BiFunction reducer; @@ -4965,13 +5173,13 @@ public class ConcurrentHashMap extends AbstractMap } K r = null; for (Node p; (p = advance()) != null; ) { - K u = (K)p.key; + K u = p.key; r = (r == null) ? u : u == null ? r : reducer.apply(r, u); } result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - ReduceKeysTask + @SuppressWarnings("unchecked") ReduceKeysTask t = (ReduceKeysTask)c, s = t.rights; while (s != null) { @@ -4986,6 +5194,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ReduceValuesTask extends BulkTask { final BiFunction reducer; @@ -5017,7 +5226,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - ReduceValuesTask + @SuppressWarnings("unchecked") ReduceValuesTask t = (ReduceValuesTask)c, s = t.rights; while (s != null) { @@ -5032,6 +5241,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class ReduceEntriesTask extends BulkTask> { final BiFunction, Map.Entry, ? extends Map.Entry> reducer; @@ -5061,7 +5271,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - ReduceEntriesTask + @SuppressWarnings("unchecked") ReduceEntriesTask t = (ReduceEntriesTask)c, s = t.rights; while (s != null) { @@ -5076,6 +5286,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceKeysTask extends BulkTask { final Function transformer; @@ -5107,13 +5318,13 @@ public class ConcurrentHashMap extends AbstractMap U r = null; for (Node p; (p = advance()) != null; ) { U u; - if ((u = transformer.apply((K)p.key)) != null) + if ((u = transformer.apply(p.key)) != null) r = (r == null) ? u : reducer.apply(r, u); } result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceKeysTask + @SuppressWarnings("unchecked") MapReduceKeysTask t = (MapReduceKeysTask)c, s = t.rights; while (s != null) { @@ -5128,6 +5339,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceValuesTask extends BulkTask { final Function transformer; @@ -5165,7 +5377,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceValuesTask + @SuppressWarnings("unchecked") MapReduceValuesTask t = (MapReduceValuesTask)c, s = t.rights; while (s != null) { @@ -5180,6 +5392,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceEntriesTask extends BulkTask { final Function, ? extends U> transformer; @@ -5217,7 +5430,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceEntriesTask + @SuppressWarnings("unchecked") MapReduceEntriesTask t = (MapReduceEntriesTask)c, s = t.rights; while (s != null) { @@ -5232,6 +5445,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceMappingsTask extends BulkTask { final BiFunction transformer; @@ -5263,13 +5477,13 @@ public class ConcurrentHashMap extends AbstractMap U r = null; for (Node p; (p = advance()) != null; ) { U u; - if ((u = transformer.apply((K)p.key, p.val)) != null) + if ((u = transformer.apply(p.key, p.val)) != null) r = (r == null) ? u : reducer.apply(r, u); } result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceMappingsTask + @SuppressWarnings("unchecked") MapReduceMappingsTask t = (MapReduceMappingsTask)c, s = t.rights; while (s != null) { @@ -5284,6 +5498,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceKeysToDoubleTask extends BulkTask { final ToDoubleFunction transformer; @@ -5316,11 +5531,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node p; (p = advance()) != null; ) - r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key)); + r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key)); result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceKeysToDoubleTask + @SuppressWarnings("unchecked") MapReduceKeysToDoubleTask t = (MapReduceKeysToDoubleTask)c, s = t.rights; while (s != null) { @@ -5332,6 +5547,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceValuesToDoubleTask extends BulkTask { final ToDoubleFunction transformer; @@ -5368,7 +5584,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceValuesToDoubleTask + @SuppressWarnings("unchecked") MapReduceValuesToDoubleTask t = (MapReduceValuesToDoubleTask)c, s = t.rights; while (s != null) { @@ -5380,6 +5596,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceEntriesToDoubleTask extends BulkTask { final ToDoubleFunction> transformer; @@ -5416,7 +5633,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceEntriesToDoubleTask + @SuppressWarnings("unchecked") MapReduceEntriesToDoubleTask t = (MapReduceEntriesToDoubleTask)c, s = t.rights; while (s != null) { @@ -5428,6 +5645,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceMappingsToDoubleTask extends BulkTask { final ToDoubleBiFunction transformer; @@ -5460,11 +5678,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node p; (p = advance()) != null; ) - r = reducer.applyAsDouble(r, transformer.applyAsDouble((K)p.key, p.val)); + r = reducer.applyAsDouble(r, transformer.applyAsDouble(p.key, p.val)); result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceMappingsToDoubleTask + @SuppressWarnings("unchecked") MapReduceMappingsToDoubleTask t = (MapReduceMappingsToDoubleTask)c, s = t.rights; while (s != null) { @@ -5476,6 +5694,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceKeysToLongTask extends BulkTask { final ToLongFunction transformer; @@ -5508,11 +5727,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node p; (p = advance()) != null; ) - r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key)); + r = reducer.applyAsLong(r, transformer.applyAsLong(p.key)); result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceKeysToLongTask + @SuppressWarnings("unchecked") MapReduceKeysToLongTask t = (MapReduceKeysToLongTask)c, s = t.rights; while (s != null) { @@ -5524,6 +5743,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceValuesToLongTask extends BulkTask { final ToLongFunction transformer; @@ -5560,7 +5780,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceValuesToLongTask + @SuppressWarnings("unchecked") MapReduceValuesToLongTask t = (MapReduceValuesToLongTask)c, s = t.rights; while (s != null) { @@ -5572,6 +5792,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceEntriesToLongTask extends BulkTask { final ToLongFunction> transformer; @@ -5608,7 +5829,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceEntriesToLongTask + @SuppressWarnings("unchecked") MapReduceEntriesToLongTask t = (MapReduceEntriesToLongTask)c, s = t.rights; while (s != null) { @@ -5620,6 +5841,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceMappingsToLongTask extends BulkTask { final ToLongBiFunction transformer; @@ -5652,11 +5874,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node p; (p = advance()) != null; ) - r = reducer.applyAsLong(r, transformer.applyAsLong((K)p.key, p.val)); + r = reducer.applyAsLong(r, transformer.applyAsLong(p.key, p.val)); result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceMappingsToLongTask + @SuppressWarnings("unchecked") MapReduceMappingsToLongTask t = (MapReduceMappingsToLongTask)c, s = t.rights; while (s != null) { @@ -5668,6 +5890,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceKeysToIntTask extends BulkTask { final ToIntFunction transformer; @@ -5700,11 +5923,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node p; (p = advance()) != null; ) - r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key)); + r = reducer.applyAsInt(r, transformer.applyAsInt(p.key)); result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceKeysToIntTask + @SuppressWarnings("unchecked") MapReduceKeysToIntTask t = (MapReduceKeysToIntTask)c, s = t.rights; while (s != null) { @@ -5716,6 +5939,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceValuesToIntTask extends BulkTask { final ToIntFunction transformer; @@ -5752,7 +5976,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceValuesToIntTask + @SuppressWarnings("unchecked") MapReduceValuesToIntTask t = (MapReduceValuesToIntTask)c, s = t.rights; while (s != null) { @@ -5764,6 +5988,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceEntriesToIntTask extends BulkTask { final ToIntFunction> transformer; @@ -5800,7 +6025,7 @@ public class ConcurrentHashMap extends AbstractMap result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceEntriesToIntTask + @SuppressWarnings("unchecked") MapReduceEntriesToIntTask t = (MapReduceEntriesToIntTask)c, s = t.rights; while (s != null) { @@ -5812,6 +6037,7 @@ public class ConcurrentHashMap extends AbstractMap } } + @SuppressWarnings("serial") static final class MapReduceMappingsToIntTask extends BulkTask { final ToIntBiFunction transformer; @@ -5844,11 +6070,11 @@ public class ConcurrentHashMap extends AbstractMap rights, transformer, r, reducer)).fork(); } for (Node p; (p = advance()) != null; ) - r = reducer.applyAsInt(r, transformer.applyAsInt((K)p.key, p.val)); + r = reducer.applyAsInt(r, transformer.applyAsInt(p.key, p.val)); result = r; CountedCompleter c; for (c = firstComplete(); c != null; c = c.nextComplete()) { - MapReduceMappingsToIntTask + @SuppressWarnings("unchecked") MapReduceMappingsToIntTask t = (MapReduceMappingsToIntTask)c, s = t.rights; while (s != null) { @@ -5885,12 +6111,12 @@ public class ConcurrentHashMap extends AbstractMap (k.getDeclaredField("baseCount")); CELLSBUSY = U.objectFieldOffset (k.getDeclaredField("cellsBusy")); - Class ck = Cell.class; + Class ck = CounterCell.class; CELLVALUE = U.objectFieldOffset (ck.getDeclaredField("value")); - Class sc = Node[].class; - ABASE = U.arrayBaseOffset(sc); - int scale = U.arrayIndexScale(sc); + Class ak = Node[].class; + ABASE = U.arrayBaseOffset(ak); + int scale = U.arrayIndexScale(ak); if ((scale & (scale - 1)) != 0) throw new Error("data type scale not a power of two"); ASHIFT = 31 - Integer.numberOfLeadingZeros(scale); diff --git a/src/share/classes/java/util/concurrent/ConcurrentMap.java b/src/share/classes/java/util/concurrent/ConcurrentMap.java index f0c42bb321a8b8f040ff7283a1ad9a18217a8e60..6c902fa6868b6f1d0116f7dfdfc215a84460d8f0 100644 --- a/src/share/classes/java/util/concurrent/ConcurrentMap.java +++ b/src/share/classes/java/util/concurrent/ConcurrentMap.java @@ -39,8 +39,8 @@ import java.util.Objects; import java.util.function.BiFunction; /** - * A {@link java.util.Map} providing additional atomic - * {@code putIfAbsent}, {@code remove}, and {@code replace} methods. + * A {@link java.util.Map} providing thread safety and atomicity + * guarantees. * *

      Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a @@ -89,11 +89,11 @@ public interface ConcurrentMap extends Map { * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, or - * null if there was no mapping for the key. - * (A null return can also indicate that the map - * previously associated null with the key, + * {@code null} if there was no mapping for the key. + * (A {@code null} return can also indicate that the map + * previously associated {@code null} with the key, * if the implementation supports null values.) - * @throws UnsupportedOperationException if the put operation + * @throws UnsupportedOperationException if the {@code put} operation * is not supported by this map * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map diff --git a/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java b/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java index 1d096f0c52d66f626bfaa5eb43bf23a9ea1039ef..7f54eab7b4e2184be2979c08a9d3e56d194e8d03 100644 --- a/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java +++ b/src/share/classes/java/util/concurrent/ConcurrentNavigableMap.java @@ -101,7 +101,7 @@ public interface ConcurrentNavigableMap * reflected in the descending map, and vice-versa. * *

      The returned map has an ordering equivalent to - * {@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator()). + * {@link Collections#reverseOrder(Comparator) Collections.reverseOrder}{@code (comparator())}. * The expression {@code m.descendingMap().descendingMap()} returns a * view of {@code m} essentially equivalent to {@code m}. * diff --git a/src/share/classes/java/util/stream/AbstractShortCircuitTask.java b/src/share/classes/java/util/stream/AbstractShortCircuitTask.java index 06da65485dd6370af49a1b48203c03cf41b71b49..7a102e80d8e4d98b1009ce90bdccfbcdbab32456 100644 --- a/src/share/classes/java/util/stream/AbstractShortCircuitTask.java +++ b/src/share/classes/java/util/stream/AbstractShortCircuitTask.java @@ -92,22 +92,51 @@ abstract class AbstractShortCircuitTask rs = spliterator, ls; + long sizeEstimate = rs.estimateSize(); + long sizeThreshold = getTargetSize(sizeEstimate); + boolean forkRight = false; + @SuppressWarnings("unchecked") K task = (K) this; + AtomicReference sr = sharedResult; + R result; + while ((result = sr.get()) == null) { + if (task.taskCanceled()) { + result = task.getEmptyResult(); + break; + } + if (sizeEstimate <= sizeThreshold || (ls = rs.trySplit()) == null) { + result = task.doLeaf(); + break; + } + K leftChild, rightChild, taskToFork; + task.leftChild = leftChild = task.makeChild(ls); + task.rightChild = rightChild = task.makeChild(rs); + task.setPendingCount(1); + if (forkRight) { + forkRight = false; + rs = ls; + task = leftChild; + taskToFork = rightChild; + } + else { + forkRight = true; + task = rightChild; + taskToFork = leftChild; + } + taskToFork.fork(); + sizeEstimate = rs.estimateSize(); } + task.setLocalResult(result); + task.tryComplete(); } + /** * Declares that a globally valid result has been found. If another task has * not already found the answer, the result is installed in diff --git a/src/share/classes/java/util/stream/AbstractTask.java b/src/share/classes/java/util/stream/AbstractTask.java index 75fc3a11f6048a66e96c0d0015563cfa5cde725e..b8344e84c59f3a9c48c0c99440aea2ad166e4e4b 100644 --- a/src/share/classes/java/util/stream/AbstractTask.java +++ b/src/share/classes/java/util/stream/AbstractTask.java @@ -102,7 +102,7 @@ abstract class AbstractTask spliterator; /** Target leaf size, common to all tasks in a computation */ - protected final long targetSize; + protected long targetSize; // may be laziliy initialized /** * The left child. @@ -134,7 +134,7 @@ abstract class AbstractTask targetSize); - // @@@ May additionally want to fold in pool characteristics such as surplus task count - } - - /** - * Returns a suggestion whether it is adviseable to split this task based on - * target size and other considerations. - * - * @return {@code true} if a split is advised otherwise {@code false} - */ - public boolean suggestSplit() { - return suggestSplit(spliterator, targetSize); + protected final long getTargetSize(long sizeEstimate) { + long s; + return ((s = targetSize) != 0 ? s : + (targetSize = suggestTargetSize(sizeEstimate))); } /** @@ -285,43 +271,46 @@ abstract class AbstractTask - * Computing will continue for rightmost tasks while a task can be computed - * as determined by {@link #canCompute()} and that task should and can be - * split into left and right tasks. - * - *

      - * The rightmost tasks are computed in a loop rather than recursively to - * avoid potential stack overflows when computing with a right-balanced - * tree, such as that produced when splitting with a {@link Spliterator} - * created from an {@link java.util.Iterator}. + *

      The method is structured to conserve resources across a + * range of uses. The loop continues with one of the child tasks + * when split, to avoid deep recursion. To cope with spliterators + * that may be systematically biased toward left-heavy or + * right-heavy splits, we alternate which child is forked versus + * continued in the loop. */ @Override - public final void compute() { - @SuppressWarnings("unchecked") - K task = (K) this; - while (task.canCompute()) { - Spliterator split; - if (!task.suggestSplit() || (split = task.spliterator.trySplit()) == null) { - task.setLocalResult(task.doLeaf()); - task.tryComplete(); - return; + public void compute() { + Spliterator rs = spliterator, ls; // right, left spliterators + long sizeEstimate = rs.estimateSize(); + long sizeThreshold = getTargetSize(sizeEstimate); + boolean forkRight = false; + @SuppressWarnings("unchecked") K task = (K) this; + while (sizeEstimate > sizeThreshold && (ls = rs.trySplit()) != null) { + K leftChild, rightChild, taskToFork; + task.leftChild = leftChild = task.makeChild(ls); + task.rightChild = rightChild = task.makeChild(rs); + task.setPendingCount(1); + if (forkRight) { + forkRight = false; + rs = ls; + task = leftChild; + taskToFork = rightChild; } else { - K l = task.leftChild = task.makeChild(split); - K r = task.rightChild = task.makeChild(task.spliterator); - task.spliterator = null; - task.setPendingCount(1); - l.fork(); - task = r; + forkRight = true; + task = rightChild; + taskToFork = leftChild; } + taskToFork.fork(); + sizeEstimate = rs.estimateSize(); } + task.setLocalResult(task.doLeaf()); + task.tryComplete(); } /** @@ -338,21 +327,6 @@ abstract class AbstractTask the output type of the stream pipeline */ - private static abstract class ForEachOp + static abstract class ForEachOp implements TerminalOp, TerminalSink { private final boolean ordered; @@ -169,7 +170,7 @@ final class ForEachOps { // Implementations /** Implementation class for reference streams */ - private static class OfRef extends ForEachOp { + static final class OfRef extends ForEachOp { final Consumer consumer; OfRef(Consumer consumer, boolean ordered) { @@ -184,7 +185,7 @@ final class ForEachOps { } /** Implementation class for {@code IntStream} */ - private static class OfInt extends ForEachOp + static final class OfInt extends ForEachOp implements Sink.OfInt { final IntConsumer consumer; @@ -205,7 +206,7 @@ final class ForEachOps { } /** Implementation class for {@code LongStream} */ - private static class OfLong extends ForEachOp + static final class OfLong extends ForEachOp implements Sink.OfLong { final LongConsumer consumer; @@ -226,7 +227,7 @@ final class ForEachOps { } /** Implementation class for {@code DoubleStream} */ - private static class OfDouble extends ForEachOp + static final class OfDouble extends ForEachOp implements Sink.OfDouble { final DoubleConsumer consumer; @@ -248,20 +249,20 @@ final class ForEachOps { } /** A {@code ForkJoinTask} for performing a parallel for-each operation */ - private static class ForEachTask extends CountedCompleter { + static final class ForEachTask extends CountedCompleter { private Spliterator spliterator; private final Sink sink; private final PipelineHelper helper; - private final long targetSize; + private long targetSize; ForEachTask(PipelineHelper helper, Spliterator spliterator, Sink sink) { super(null); - this.spliterator = spliterator; this.sink = sink; - this.targetSize = AbstractTask.suggestTargetSize(spliterator.estimateSize()); this.helper = helper; + this.spliterator = spliterator; + this.targetSize = 0L; } ForEachTask(ForEachTask parent, Spliterator spliterator) { @@ -272,28 +273,40 @@ final class ForEachOps { this.helper = parent.helper; } + // Similar to AbstractTask but doesn't need to track child tasks public void compute() { + Spliterator rightSplit = spliterator, leftSplit; + long sizeEstimate = rightSplit.estimateSize(), sizeThreshold; + if ((sizeThreshold = targetSize) == 0L) + targetSize = sizeThreshold = AbstractTask.suggestTargetSize(sizeEstimate); boolean isShortCircuit = StreamOpFlag.SHORT_CIRCUIT.isKnown(helper.getStreamAndOpFlags()); - while (true) { - if (isShortCircuit && sink.cancellationRequested()) { - propagateCompletion(); - spliterator = null; - return; + boolean forkRight = false; + Sink taskSink = sink; + ForEachTask task = this; + while (!isShortCircuit || !taskSink.cancellationRequested()) { + if (sizeEstimate <= sizeThreshold || + (leftSplit = rightSplit.trySplit()) == null) { + task.helper.copyInto(taskSink, rightSplit); + break; } - - Spliterator split; - if (!AbstractTask.suggestSplit(spliterator, targetSize) - || (split = spliterator.trySplit()) == null) { - helper.copyInto(sink, spliterator); - propagateCompletion(); - spliterator = null; - return; + ForEachTask leftTask = new ForEachTask<>(task, leftSplit); + task.addToPendingCount(1); + ForEachTask taskToFork; + if (forkRight) { + forkRight = false; + rightSplit = leftSplit; + taskToFork = task; + task = leftTask; } else { - addToPendingCount(1); - new ForEachTask<>(this, split).fork(); + forkRight = true; + taskToFork = leftTask; } + taskToFork.fork(); + sizeEstimate = rightSplit.estimateSize(); } + task.spliterator = null; + task.propagateCompletion(); } } @@ -301,7 +314,7 @@ final class ForEachOps { * A {@code ForkJoinTask} for performing a parallel for-each operation * which visits the elements in encounter order */ - private static class ForEachOrderedTask extends CountedCompleter { + static final class ForEachOrderedTask extends CountedCompleter { private final PipelineHelper helper; private Spliterator spliterator; private final long targetSize; @@ -343,39 +356,49 @@ final class ForEachOps { } private static void doCompute(ForEachOrderedTask task) { - while (true) { - Spliterator split; - if (!AbstractTask.suggestSplit(task.spliterator, task.targetSize) - || (split = task.spliterator.trySplit()) == null) { - if (task.getPendingCount() == 0) { - task.helper.wrapAndCopyInto(task.action, task.spliterator); - } - else { - Node.Builder nb = task.helper.makeNodeBuilder( - task.helper.exactOutputSizeIfKnown(task.spliterator), - size -> (T[]) new Object[size]); - task.node = task.helper.wrapAndCopyInto(nb, task.spliterator).build(); - } - task.tryComplete(); - return; + Spliterator rightSplit = task.spliterator, leftSplit; + long sizeThreshold = task.targetSize; + boolean forkRight = false; + while (rightSplit.estimateSize() > sizeThreshold && + (leftSplit = rightSplit.trySplit()) != null) { + ForEachOrderedTask leftChild = + new ForEachOrderedTask<>(task, leftSplit, task.leftPredecessor); + ForEachOrderedTask rightChild = + new ForEachOrderedTask<>(task, rightSplit, leftChild); + task.completionMap.put(leftChild, rightChild); + task.addToPendingCount(1); // forking + rightChild.addToPendingCount(1); // right pending on left child + if (task.leftPredecessor != null) { + leftChild.addToPendingCount(1); // left pending on previous subtree, except left spine + if (task.completionMap.replace(task.leftPredecessor, task, leftChild)) + task.addToPendingCount(-1); // transfer my "right child" count to my left child + else + leftChild.addToPendingCount(-1); // left child is ready to go when ready + } + ForEachOrderedTask taskToFork; + if (forkRight) { + forkRight = false; + rightSplit = leftSplit; + task = leftChild; + taskToFork = rightChild; } else { - ForEachOrderedTask leftChild = new ForEachOrderedTask<>(task, split, task.leftPredecessor); - ForEachOrderedTask rightChild = new ForEachOrderedTask<>(task, task.spliterator, leftChild); - task.completionMap.put(leftChild, rightChild); - task.addToPendingCount(1); // forking - rightChild.addToPendingCount(1); // right pending on left child - if (task.leftPredecessor != null) { - leftChild.addToPendingCount(1); // left pending on previous subtree, except left spine - if (task.completionMap.replace(task.leftPredecessor, task, leftChild)) - task.addToPendingCount(-1); // transfer my "right child" count to my left child - else - leftChild.addToPendingCount(-1); // left child is ready to go when ready - } - leftChild.fork(); + forkRight = true; task = rightChild; + taskToFork = leftChild; } + taskToFork.fork(); + } + if (task.getPendingCount() == 0) { + task.helper.wrapAndCopyInto(task.action, rightSplit); + } + else { + Node.Builder nb = task.helper.makeNodeBuilder( + task.helper.exactOutputSizeIfKnown(rightSplit), + size -> (T[]) new Object[size]); + task.node = task.helper.wrapAndCopyInto(nb, rightSplit).build(); } + task.tryComplete(); } @Override diff --git a/src/share/classes/java/util/stream/Nodes.java b/src/share/classes/java/util/stream/Nodes.java index f79a88c470b9d443d2acc8739024a21f4d7bcc87..4edf324a84c61041054b8b7af061e78094371244 100644 --- a/src/share/classes/java/util/stream/Nodes.java +++ b/src/share/classes/java/util/stream/Nodes.java @@ -1829,25 +1829,20 @@ final class Nodes { @Override public void compute() { SizedCollectorTask task = this; - while (true) { - Spliterator leftSplit; - if (!AbstractTask.suggestSplit(task.spliterator, task.targetSize) - || ((leftSplit = task.spliterator.trySplit()) == null)) { - if (task.offset + task.length >= MAX_ARRAY_SIZE) - throw new IllegalArgumentException("Stream size exceeds max array size"); - T_SINK sink = (T_SINK) task; - task.helper.wrapAndCopyInto(sink, task.spliterator); - task.propagateCompletion(); - return; - } - else { - task.setPendingCount(1); - long leftSplitSize = leftSplit.estimateSize(); - task.makeChild(leftSplit, task.offset, leftSplitSize).fork(); - task = task.makeChild(task.spliterator, task.offset + leftSplitSize, - task.length - leftSplitSize); - } - } + Spliterator rightSplit = spliterator, leftSplit; + while (rightSplit.estimateSize() > task.targetSize && + (leftSplit = rightSplit.trySplit()) != null) { + task.setPendingCount(1); + long leftSplitSize = leftSplit.estimateSize(); + task.makeChild(leftSplit, task.offset, leftSplitSize).fork(); + task = task.makeChild(rightSplit, task.offset + leftSplitSize, + task.length - leftSplitSize); + } + if (task.offset + task.length >= MAX_ARRAY_SIZE) + throw new IllegalArgumentException("Stream size exceeds max array size"); + T_SINK sink = (T_SINK) task; + task.helper.wrapAndCopyInto(sink, rightSplit); + task.propagateCompletion(); } abstract K makeChild(Spliterator spliterator, long offset, long size); diff --git a/src/share/classes/javax/management/JMX.java b/src/share/classes/javax/management/JMX.java index 7f8cc411964c08d9d3f1bd8441d68326dfe8e99f..fe5d9093ac277cde6e93c9cf8d45c0fe8be10b1f 100644 --- a/src/share/classes/javax/management/JMX.java +++ b/src/share/classes/javax/management/JMX.java @@ -160,6 +160,10 @@ public class JMX { * example, then the return type is {@code MyMBean}. * * @return the new proxy instance. + * + * @throws IllegalArgumentException if {@code interfaceClass} is not + * a compliant MBean + * interface */ public static T newMBeanProxy(MBeanServerConnection connection, ObjectName objectName, @@ -200,6 +204,10 @@ public class JMX { * example, then the return type is {@code MyMBean}. * * @return the new proxy instance. + * + * @throws IllegalArgumentException if {@code interfaceClass} is not + * a compliant MBean + * interface */ public static T newMBeanProxy(MBeanServerConnection connection, ObjectName objectName, @@ -298,6 +306,9 @@ public class JMX { * example, then the return type is {@code MyMXBean}. * * @return the new proxy instance. + * + * @throws IllegalArgumentException if {@code interfaceClass} is not + * a {@link javax.management.MXBean compliant MXBean interface} */ public static T newMXBeanProxy(MBeanServerConnection connection, ObjectName objectName, @@ -338,6 +349,9 @@ public class JMX { * example, then the return type is {@code MyMXBean}. * * @return the new proxy instance. + * + * @throws IllegalArgumentException if {@code interfaceClass} is not + * a {@link javax.management.MXBean compliant MXBean interface} */ public static T newMXBeanProxy(MBeanServerConnection connection, ObjectName objectName, @@ -348,21 +362,25 @@ public class JMX { /** *

      Test whether an interface is an MXBean interface. - * An interface is an MXBean interface if it is annotated - * {@link MXBean @MXBean} or {@code @MXBean(true)} + * An interface is an MXBean interface if it is public, + * annotated {@link MXBean @MXBean} or {@code @MXBean(true)} * or if it does not have an {@code @MXBean} annotation * and its name ends with "{@code MXBean}".

      * * @param interfaceClass The candidate interface. * - * @return true if {@code interfaceClass} is an interface and - * meets the conditions described. + * @return true if {@code interfaceClass} is a + * {@link javax.management.MXBean compliant MXBean interface} * * @throws NullPointerException if {@code interfaceClass} is null. */ public static boolean isMXBeanInterface(Class interfaceClass) { if (!interfaceClass.isInterface()) return false; + if (!Modifier.isPublic(interfaceClass.getModifiers()) && + !Introspector.ALLOW_NONPUBLIC_MBEAN) { + return false; + } MXBean a = interfaceClass.getAnnotation(MXBean.class); if (a != null) return a.value(); @@ -389,9 +407,6 @@ public class JMX { boolean notificationEmitter, boolean isMXBean) { - if (System.getSecurityManager() != null) { - checkProxyInterface(interfaceClass); - } try { if (isMXBean) { // Check interface for MXBean compliance @@ -419,17 +434,4 @@ public class JMX { handler); return interfaceClass.cast(proxy); } - - /** - * Checks for the M(X)Bean proxy interface being public and not restricted - * @param interfaceClass MBean proxy interface - * @throws SecurityException when the proxy interface comes from a restricted - * package or is not public - */ - private static void checkProxyInterface(Class interfaceClass) { - if (!Modifier.isPublic(interfaceClass.getModifiers())) { - throw new SecurityException("mbean proxy interface non-public"); - } - ReflectUtil.checkPackageAccess(interfaceClass); - } } diff --git a/src/share/classes/javax/management/MBeanServerInvocationHandler.java b/src/share/classes/javax/management/MBeanServerInvocationHandler.java index bc174fb303f1555d8ea341ae4101a4818294fba2..485dec8b59c3f881bf4a487e6eaa940f705a13bd 100644 --- a/src/share/classes/javax/management/MBeanServerInvocationHandler.java +++ b/src/share/classes/javax/management/MBeanServerInvocationHandler.java @@ -225,7 +225,7 @@ public class MBeanServerInvocationHandler implements InvocationHandler { * * @return the new proxy instance. * - * @see JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class) + * @see JMX#newMBeanProxy(MBeanServerConnection, ObjectName, Class, boolean) */ public static T newProxyInstance(MBeanServerConnection connection, ObjectName objectName, diff --git a/src/share/classes/javax/management/MXBean.java b/src/share/classes/javax/management/MXBean.java index 4ff10d360afa4cd4ea4db815bb567b2b6108fd35..e4c920651bc8bb8e21d33a32c7a3ed407bcfe027 100644 --- a/src/share/classes/javax/management/MXBean.java +++ b/src/share/classes/javax/management/MXBean.java @@ -54,9 +54,9 @@ import javax.management.openmbean.TabularType; /**

      Annotation to mark an interface explicitly as being an MXBean interface, or as not being an MXBean interface. By default, an - interface is an MXBean interface if its name ends with {@code - MXBean}, as in {@code SomethingMXBean}. The following interfaces - are MXBean interfaces:

      + interface is an MXBean interface if it is public and its name ends + with {@code MXBean}, as in {@code SomethingMXBean}. The following + interfaces are MXBean interfaces:

           public interface WhatsitMXBean {}
      @@ -71,6 +71,8 @@ import javax.management.openmbean.TabularType;
           

      The following interfaces are not MXBean interfaces:

      +    interface NonPublicInterfaceNotMXBean{}
      +
           public interface Whatsit3Interface{}
       
           @MXBean(false)
      diff --git a/src/share/classes/javax/management/package.html b/src/share/classes/javax/management/package.html
      index 4c9b012cf22bba394a98618bc40a23d1d34a46a3..9cd9ef81766c959e5d60614ba4a2213c2c4b8aaf 100644
      --- a/src/share/classes/javax/management/package.html
      +++ b/src/share/classes/javax/management/package.html
      @@ -53,8 +53,8 @@ questions.
       
               

      The fundamental notion of the JMX API is the MBean. An MBean is a named managed object representing a - resource. It has a management interface consisting - of:

      + resource. It has a management interface + which must be public and consist of:

      • named and typed attributes that can be read and/or diff --git a/src/share/classes/javax/script/ScriptEngineFactory.java b/src/share/classes/javax/script/ScriptEngineFactory.java index 298b4ad7b4130c9110248a425d8e4fae47ce5eee..e2596f0da1af4a4068fd903eed0b49c1a14d618d 100644 --- a/src/share/classes/javax/script/ScriptEngineFactory.java +++ b/src/share/classes/javax/script/ScriptEngineFactory.java @@ -196,18 +196,17 @@ public interface ScriptEngineFactory { /** - * Returns A valid scripting language executable progam with given statements. + * Returns a valid scripting language executable progam with given statements. * For instance an implementation for a PHP engine might be: *

        *

        {@code
              * public String getProgram(String... statements) {
        -     *      $retval = "";
        -     *
        +     *      return retval += "?>";
              * }
              * }
        * diff --git a/src/share/classes/sun/management/ManagementFactoryHelper.java b/src/share/classes/sun/management/ManagementFactoryHelper.java index 6e875a279146788650a8a6e3a71ade6abc9e8b79..43079e986d672f2b0e8b2d44ed115b903fc988d2 100644 --- a/src/share/classes/sun/management/ManagementFactoryHelper.java +++ b/src/share/classes/sun/management/ManagementFactoryHelper.java @@ -147,18 +147,20 @@ public class ManagementFactoryHelper { } } - // The logging MXBean object is an instance of - // PlatformLoggingMXBean and java.util.logging.LoggingMXBean - // but it can't directly implement two MXBean interfaces - // as a compliant MXBean implements exactly one MXBean interface, - // or if it implements one interface that is a subinterface of - // all the others; otherwise, it is a non-compliant MXBean - // and MBeanServer will throw NotCompliantMBeanException. - // See the Definition of an MXBean section in javax.management.MXBean spec. - // - // To create a compliant logging MXBean, define a LoggingMXBean interface - // that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean - interface LoggingMXBean + /** + * The logging MXBean object is an instance of + * PlatformLoggingMXBean and java.util.logging.LoggingMXBean + * but it can't directly implement two MXBean interfaces + * as a compliant MXBean implements exactly one MXBean interface, + * or if it implements one interface that is a subinterface of + * all the others; otherwise, it is a non-compliant MXBean + * and MBeanServer will throw NotCompliantMBeanException. + * See the Definition of an MXBean section in javax.management.MXBean spec. + * + * To create a compliant logging MXBean, define a LoggingMXBean interface + * that extend PlatformLoggingMXBean and j.u.l.LoggingMXBean + */ + public interface LoggingMXBean extends PlatformLoggingMXBean, java.util.logging.LoggingMXBean { } diff --git a/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java b/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java index b66f7c01190fc3bf340a727e2646e9c2f90d9bea..e6cd26e3c9e8b24eb015e6fa39b159b65dd03e6c 100644 --- a/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java +++ b/test/com/sun/management/HotSpotDiagnosticMXBean/SetVMOption.java @@ -27,6 +27,7 @@ * @summary Basic Test for HotSpotDiagnosticMXBean.setVMOption() * and getDiagnosticOptions(). * @author Mandy Chung + * @author Jaroslav Bachorik * * @run main/othervm -XX:+PrintGCDetails SetVMOption */ @@ -36,7 +37,6 @@ import java.util.*; import com.sun.management.HotSpotDiagnosticMXBean; import com.sun.management.VMOption; import com.sun.management.VMOption.Origin; -import sun.misc.Version; public class SetVMOption { private static String PRINT_GC_DETAILS = "PrintGCDetails"; @@ -47,17 +47,8 @@ public class SetVMOption { private static HotSpotDiagnosticMXBean mbean; public static void main(String[] args) throws Exception { - List list = - ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class); - - // The following test is transitional only and should be removed - // once build 52 is promoted. - int build = Version.jvmBuildNumber(); - if (build > 0 && build < 52) { - // JVM support is integrated in build 52 - // this test is skipped if running with VM earlier than 52 - return; - } + mbean = + ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class); VMOption option = findPrintGCDetailsOption(); if (!option.getValue().equalsIgnoreCase(EXPECTED_VALUE)) { diff --git a/test/java/io/File/CheckPermission.java b/test/java/io/File/CheckPermission.java new file mode 100644 index 0000000000000000000000000000000000000000..33fffddd283733e9886b9c87ee98f7f2a23376bb --- /dev/null +++ b/test/java/io/File/CheckPermission.java @@ -0,0 +1,379 @@ +/* + * 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. + * + * 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. + */ + +/* @test + * @bug 8017212 + * @summary Examine methods in File.java that access the file system do the + * right permission check when a security manager exists. + * @author Dan Xu + */ + +import java.io.File; +import java.io.FilenameFilter; +import java.io.FileFilter; +import java.io.IOException; +import java.security.Permission; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class CheckPermission { + + private static final String CHECK_PERMISSION_TEST = "CheckPermissionTest"; + + public enum FileOperation { + READ, WRITE, DELETE, EXEC + } + + static class Checks { + private List permissionsChecked = new ArrayList<>(); + private Set propertiesChecked = new HashSet<>(); + + private Map> fileOperationChecked = + new EnumMap<>(FileOperation.class); + + List permissionsChecked() { + return permissionsChecked; + } + + Set propertiesChecked() { + return propertiesChecked; + } + + List fileOperationChecked(FileOperation op) { + return fileOperationChecked.get(op); + } + + void addFileOperation(FileOperation op, String file) { + List opList = fileOperationChecked.get(op); + if (opList == null) { + opList = new ArrayList<>(); + fileOperationChecked.put(op, opList); + } + opList.add(file); + } + } + + static ThreadLocal myChecks = new ThreadLocal<>(); + + static void prepare() { + myChecks.set(new Checks()); + } + + static class LoggingSecurityManager extends SecurityManager { + static void install() { + System.setSecurityManager(new LoggingSecurityManager()); + } + + private void checkFileOperation(FileOperation op, String file) { + Checks checks = myChecks.get(); + if (checks != null) + checks.addFileOperation(op, file); + } + + @Override + public void checkRead(String file) { + checkFileOperation(FileOperation.READ, file); + } + + @Override + public void checkWrite(String file) { + checkFileOperation(FileOperation.WRITE, file); + } + + @Override + public void checkDelete(String file) { + checkFileOperation(FileOperation.DELETE, file); + } + + @Override + public void checkExec(String file) { + checkFileOperation(FileOperation.EXEC, file); + } + + @Override + public void checkPermission(Permission perm) { + Checks checks = myChecks.get(); + if (checks != null) + checks.permissionsChecked().add(perm); + } + + @Override + public void checkPropertyAccess(String key) { + Checks checks = myChecks.get(); + if (checks != null) + checks.propertiesChecked().add(key); + } + } + + static void assertCheckPermission(Class type, + String name) + { + for (Permission perm : myChecks.get().permissionsChecked()) { + if (type.isInstance(perm) && perm.getName().equals(name)) + return; + } + throw new RuntimeException(type.getName() + "(\"" + name + + "\") not checked"); + } + + static void assertCheckPropertyAccess(String key) { + if (!myChecks.get().propertiesChecked().contains(key)) + throw new RuntimeException("Property " + key + " not checked"); + } + + static void assertChecked(File file, List list) { + if (list != null && !list.isEmpty()) { + for (String path : list) { + if (path.equals(file.getPath())) + return; + } + } + throw new RuntimeException("Access not checked"); + } + + static void assertNotChecked(File file, List list) { + if (list != null && !list.isEmpty()) { + for (String path : list) { + if (path.equals(file.getPath())) + throw new RuntimeException("Access checked"); + } + } + } + + static void assertCheckOperation(File file, Set ops) { + for (FileOperation op : ops) + assertChecked(file, myChecks.get().fileOperationChecked(op)); + } + + static void assertNotCheckOperation(File file, Set ops) { + for (FileOperation op : ops) + assertNotChecked(file, myChecks.get().fileOperationChecked(op)); + } + + static void assertOnlyCheckOperation(File file, + EnumSet ops) + { + assertCheckOperation(file, ops); + assertNotCheckOperation(file, EnumSet.complementOf(ops)); + } + + static File testFile, another; + + static void setup() { + testFile = new File(CHECK_PERMISSION_TEST + System.currentTimeMillis()); + if (testFile.exists()) { + testFile.delete(); + } + + another = new File(CHECK_PERMISSION_TEST + "Another" + + System.currentTimeMillis()); + if (another.exists()) { + another.delete(); + } + + LoggingSecurityManager.install(); + } + + public static void main(String[] args) throws IOException { + setup(); + + prepare(); + testFile.canRead(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.canWrite(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.exists(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.isDirectory(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.isFile(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.isHidden(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.lastModified(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.length(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.createNewFile(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.list(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.list(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return false; + } + }); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.listFiles(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return false; + } + }); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.listFiles(new FileFilter() { + @Override + public boolean accept(File file) { + return false; + } + }); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + + prepare(); + testFile.mkdir(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + if (testFile.exists()) { + prepare(); + testFile.mkdirs(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + } + + if (!another.exists()) { + prepare(); + another.mkdirs(); + assertOnlyCheckOperation(another, + EnumSet.of(FileOperation.READ, FileOperation.WRITE)); + } + + prepare(); + another.delete(); + assertOnlyCheckOperation(another, EnumSet.of(FileOperation.DELETE)); + + prepare(); + boolean renRst = testFile.renameTo(another); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + assertOnlyCheckOperation(another, EnumSet.of(FileOperation.WRITE)); + + if (renRst) { + if (testFile.exists()) + throw new RuntimeException(testFile + " is already renamed to " + + another); + testFile = another; + } + + prepare(); + testFile.setLastModified(0); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setReadOnly(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setWritable(true, true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setWritable(true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setReadable(true, true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setReadable(true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setExecutable(true, true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.setExecutable(true); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.WRITE)); + + prepare(); + testFile.canExecute(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.EXEC)); + + prepare(); + testFile.getTotalSpace(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + assertCheckPermission(RuntimePermission.class, + "getFileSystemAttributes"); + + prepare(); + testFile.getFreeSpace(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + assertCheckPermission(RuntimePermission.class, + "getFileSystemAttributes"); + + prepare(); + testFile.getUsableSpace(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.READ)); + assertCheckPermission(RuntimePermission.class, + "getFileSystemAttributes"); + + prepare(); + File tmpFile = File.createTempFile(CHECK_PERMISSION_TEST, null); + assertOnlyCheckOperation(tmpFile, EnumSet.of(FileOperation.WRITE)); + tmpFile.delete(); + assertCheckOperation(tmpFile, EnumSet.of(FileOperation.DELETE)); + + prepare(); + tmpFile = File.createTempFile(CHECK_PERMISSION_TEST, null, null); + assertOnlyCheckOperation(tmpFile, EnumSet.of(FileOperation.WRITE)); + tmpFile.delete(); + assertCheckOperation(tmpFile, EnumSet.of(FileOperation.DELETE)); + + prepare(); + testFile.deleteOnExit(); + assertOnlyCheckOperation(testFile, EnumSet.of(FileOperation.DELETE)); + } +} diff --git a/test/java/io/File/NulFile.java b/test/java/io/File/NulFile.java index c7cff6aa81dc57caf858bf0dc7596fe7dcd196ab..4b83d64791e8f41f72f37944bda68a4896e1fbab 100644 --- a/test/java/io/File/NulFile.java +++ b/test/java/io/File/NulFile.java @@ -612,8 +612,13 @@ public class NulFile { try { File.createTempFile(prefix, suffix, directory); } catch (IOException ex) { - if (ExceptionMsg.equals(ex.getMessage())) + String err = "Unable to create temporary file"; + if (err.equals(ex.getMessage())) exceptionThrown = true; + else { + throw new RuntimeException("Get IOException with message, " + + ex.getMessage() + ", expect message, "+ err); + } } } if (!exceptionThrown) { diff --git a/test/java/io/File/createTempFile/SpecialTempFile.java b/test/java/io/File/createTempFile/SpecialTempFile.java index 20d6ed8cd82522c74c299628e45250d597259224..9a4cc01c5ffcaf2f84df1b329cfc98cb88852497 100644 --- a/test/java/io/File/createTempFile/SpecialTempFile.java +++ b/test/java/io/File/createTempFile/SpecialTempFile.java @@ -23,9 +23,8 @@ /* * @test - * @bug 8013827 8011950 + * @bug 8013827 8011950 8017212 * @summary Check whether File.createTempFile can handle special parameters - * on Windows platforms * @author Dan Xu */ @@ -64,6 +63,17 @@ public class SpecialTempFile { } public static void main(String[] args) throws Exception { + // Common test + final String name = "SpecialTempFile"; + File f = new File(System.getProperty("java.io.tmpdir"), name); + if (!f.exists()) { + f.createNewFile(); + } + String[] nulPre = { name + "\u0000" }; + String[] nulSuf = { ".test" }; + test("NulName", nulPre, nulSuf); + + // Windows tests if (!System.getProperty("os.name").startsWith("Windows")) return; diff --git a/test/java/lang/ref/OOMEInReferenceHandler.java b/test/java/lang/ref/OOMEInReferenceHandler.java index da7db6f36606082f7e13cca228a00a2cb59ca345..39848fa4aab4ff0828f4770ad8deecf5ff1b970c 100644 --- a/test/java/lang/ref/OOMEInReferenceHandler.java +++ b/test/java/lang/ref/OOMEInReferenceHandler.java @@ -23,9 +23,9 @@ /** * @test - * @bug 7038914 + * @bug 7038914 8016341 * @summary Verify that the reference handler does not die after an OOME allocating the InterruptedException object - * @run main/othervm -Xmx16M -XX:-UseTLAB OOMEInReferenceHandler + * @run main/othervm -Xmx24M -XX:-UseTLAB OOMEInReferenceHandler * @author peter.levart@gmail.com */ @@ -107,6 +107,6 @@ public class OOMEInReferenceHandler { } // no sure answer after 10 seconds - throw new IllegalStateException("Reference Handler thread stuck."); + throw new IllegalStateException("Reference Handler thread stuck. weakRef.get(): " + weakRef.get()); } } diff --git a/test/java/math/BigDecimal/StrippingZerosTest.java b/test/java/math/BigDecimal/StrippingZerosTest.java index d0b1753ab38d06634ff13cb92779a86c7eefc9bb..0c28c9ca311fbb93bdfe6523b8ecb49e4b09f58d 100644 --- a/test/java/math/BigDecimal/StrippingZerosTest.java +++ b/test/java/math/BigDecimal/StrippingZerosTest.java @@ -45,8 +45,17 @@ public class StrippingZerosTest { {new BigDecimal("1234.56780"), new BigDecimal("1234.5678")}, {new BigDecimal("1234.567800000"), new BigDecimal("1234.5678")}, {new BigDecimal("0"), new BigDecimal("0")}, - {new BigDecimal("0e100"), new BigDecimal("0e100")}, - {new BigDecimal("0e-100"), new BigDecimal("0e-100")}, + {new BigDecimal("0e2"), BigDecimal.ZERO}, + {new BigDecimal("0e-2"), BigDecimal.ZERO}, + {new BigDecimal("0e42"), BigDecimal.ZERO}, + {new BigDecimal("+0e42"), BigDecimal.ZERO}, + {new BigDecimal("-0e42"), BigDecimal.ZERO}, + {new BigDecimal("0e-42"), BigDecimal.ZERO}, + {new BigDecimal("+0e-42"), BigDecimal.ZERO}, + {new BigDecimal("-0e-42"), BigDecimal.ZERO}, + {new BigDecimal("0e-2"), BigDecimal.ZERO}, + {new BigDecimal("0e100"), BigDecimal.ZERO}, + {new BigDecimal("0e-100"), BigDecimal.ZERO}, {new BigDecimal("10"), new BigDecimal("1e1")}, {new BigDecimal("20"), new BigDecimal("2e1")}, {new BigDecimal("100"), new BigDecimal("1e2")}, diff --git a/test/java/util/Collections/UnmodifiableMapEntrySet.java b/test/java/util/Collections/UnmodifiableMapEntrySet.java new file mode 100644 index 0000000000000000000000000000000000000000..d7945d18f2e6c9515d2709b640cbbb6637a86450 --- /dev/null +++ b/test/java/util/Collections/UnmodifiableMapEntrySet.java @@ -0,0 +1,164 @@ +/* + * 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. + * + * 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. + */ + +/** + * @test + * @run testng UnmodifiableMapEntrySet + * @summary Unit tests for wrapping classes should delegate to default methods + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Spliterator; +import java.util.TreeMap; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; + +import static org.testng.Assert.assertEquals; + +@Test(groups = "unit") +public class UnmodifiableMapEntrySet { + static Object[][] collections; + + static > M fillMap(int size, M m) { + for (int i = 0; i < size; i++) { + m.put(i, i); + } + return m; + } + + @DataProvider(name="maps") + static Object[][] mapCases() { + if (collections != null) { + return collections; + } + + List cases = new ArrayList<>(); + for (int size : new int[] {1, 2, 16}) { + cases.add(new Object[] { + String.format("new HashMap(%d)", size), + (Supplier>) + () -> Collections.unmodifiableMap(fillMap(size, new HashMap<>())) }); + cases.add(new Object[] { + String.format("new TreeMap(%d)", size), + (Supplier>) + () -> Collections.unmodifiableSortedMap(fillMap(size, new TreeMap<>())) }); + } + + return cases.toArray(new Object[0][]); + } + + static class EntryConsumer implements Consumer> { + int updates; + @Override + public void accept(Map.Entry me) { + try { + me.setValue(Integer.MAX_VALUE); + updates++; + } catch (UnsupportedOperationException e) { + } + } + + void assertNoUpdates() { + assertEquals(updates, 0, "Updates to entries"); + } + } + + void testWithEntryConsumer(Consumer c) { + EntryConsumer ec = new EntryConsumer(); + c.accept(ec); + ec.assertNoUpdates(); + } + + @Test(dataProvider = "maps") + public void testForEach(String d, Supplier> ms) { + testWithEntryConsumer( + ec -> ms.get().entrySet().forEach(ec)); + } + + @Test(dataProvider = "maps") + public void testIteratorForEachRemaining(String d, Supplier> ms) { + testWithEntryConsumer( + ec -> ms.get().entrySet().iterator().forEachRemaining(ec)); + } + + @Test(dataProvider = "maps") + public void testIteratorNext(String d, Supplier> ms) { + testWithEntryConsumer(ec -> { + for (Map.Entry me : ms.get().entrySet()) { + ec.accept(me); + } + }); + } + + @Test(dataProvider = "maps") + public void testSpliteratorForEachRemaining(String d, Supplier> ms) { + testSpliterator( + ms.get().entrySet()::spliterator, + // Higher order function returning a consumer that + // traverses all spliterator elements using an EntryConsumer + s -> ec -> s.forEachRemaining(ec)); + } + + @Test(dataProvider = "maps") + public void testSpliteratorTryAdvance(String d, Supplier> ms) { + testSpliterator( + ms.get().entrySet()::spliterator, + // Higher order function returning a consumer that + // traverses all spliterator elements using an EntryConsumer + s -> ec -> { while (s.tryAdvance(ec)); }); + } + + void testSpliterator(Supplier>> ss, + // Higher order function that given a spliterator returns a + // consumer for that spliterator which traverses elements + // using an EntryConsumer + Function>, Consumer> sc) { + testWithEntryConsumer(sc.apply(ss.get())); + + Spliterator> s = ss.get(); + Spliterator> split = s.trySplit(); + if (split != null) { + testWithEntryConsumer(sc.apply(split)); + testWithEntryConsumer(sc.apply(s)); + } + } + + @Test(dataProvider = "maps") + public void testStreamForEach(String d, Supplier> ms) { + testWithEntryConsumer(ec -> ms.get().entrySet().stream().forEach(ec)); + } + + @Test(dataProvider = "maps") + public void testParallelStreamForEach(String d, Supplier> ms) { + testWithEntryConsumer(ec -> ms.get().entrySet().parallelStream().forEach(ec)); + } +} + diff --git a/test/javax/management/MBeanServer/MBeanFallbackTest.java b/test/javax/management/MBeanServer/MBeanFallbackTest.java new file mode 100644 index 0000000000000000000000000000000000000000..dcb5e1803a40ddd05857cd4966b8422fc194f27f --- /dev/null +++ b/test/javax/management/MBeanServer/MBeanFallbackTest.java @@ -0,0 +1,94 @@ +/* + * 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. + * + * 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. + */ + +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +/* + * @test + * @bug 8010285 + * @summary Test fallback for private MBean interfaces. + * It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic" + * system property must be set before c.s.j.m.MBeanAnalyzer has been loaded. + * @author Jaroslav Bachorik + * @run clean MBeanFallbackTest + * @run build MBeanFallbackTest + * @run main MBeanFallbackTest + */ +public class MBeanFallbackTest { + private static interface PrivateMBean { + public int[] getInts(); + } + + public static class Private implements PrivateMBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + private static int failures = 0; + + public static void main(String[] args) throws Exception { + System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true"); + testPrivate(PrivateMBean.class, new Private()); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static void fail(String msg) { + failures++; + System.out.println("FAIL: " + msg); + } + + private static void success(String msg) { + System.out.println("OK: " + msg); + } + + private static void testPrivate(Class iface, Object bean) throws Exception { + try { + System.out.println("Registering a private MBean " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Compliant"); + + mbs.registerMBean(bean, on); + success("Registered a private MBean - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + fail("MBean not registered"); + } else { + throw e; + } + } + } +} diff --git a/test/javax/management/MBeanServer/MBeanTest.java b/test/javax/management/MBeanServer/MBeanTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1ac50573e5f5c6345f27a47808e9cc0478d9bf05 --- /dev/null +++ b/test/javax/management/MBeanServer/MBeanTest.java @@ -0,0 +1,158 @@ +/* + * 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. + * + * 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. + */ + +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +/* + * @test + * @bug 8010285 + * @summary General MBean test. + * @author Jaroslav Bachorik + * @run clean MBeanTest + * @run build MBeanTest + * @run main MBeanTest + */ +public class MBeanTest { + private static interface PrivateMBean { + public int[] getInts(); + } + + public static class Private implements PrivateMBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + public static interface NonCompliantMBean { + public boolean getInt(); + public boolean isInt(); + public void setInt(int a); + public void setInt(long b); + } + + public static class NonCompliant implements NonCompliantMBean { + public boolean getInt() { + return false; + } + + public boolean isInt() { + return true; + } + + public void setInt(int a) { + } + + public void setInt(long b) { + } + } + + public static interface CompliantMBean { + public boolean isFlag(); + public int getInt(); + public void setInt(int value); + } + + public static class Compliant implements CompliantMBean { + public boolean isFlag() { + return false; + } + + public int getInt() { + return 1; + } + + public void setInt(int value) { + } + } + + private static int failures = 0; + + public static void main(String[] args) throws Exception { + testCompliant(CompliantMBean.class, new Compliant()); + testNonCompliant(PrivateMBean.class, new Private()); + testNonCompliant(NonCompliantMBean.class, new NonCompliant()); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static void fail(String msg) { + failures++; + System.out.println("FAIL: " + msg); + } + + private static void success(String msg) { + System.out.println("OK: " + msg); + } + + private static void testNonCompliant(Class iface, Object bean) throws Exception { + try { + System.out.println("Registering a non-compliant MBean " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=NonCompliant"); + + mbs.registerMBean(bean, on); + + fail("Registered a non-compliant MBean - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + success("MBean not registered"); + } else { + throw e; + } + } + } + private static void testCompliant(Class iface, Object bean) throws Exception { + try { + System.out.println("Registering a compliant MBean " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Compliant"); + + mbs.registerMBean(bean, on); + success("Registered a compliant MBean - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + fail("MBean not registered"); + } else { + throw e; + } + } + } +} diff --git a/test/javax/management/mxbean/MXBeanFallbackTest.java b/test/javax/management/mxbean/MXBeanFallbackTest.java new file mode 100644 index 0000000000000000000000000000000000000000..388ffc9373d57a35801e2384728e15531b2eaa28 --- /dev/null +++ b/test/javax/management/mxbean/MXBeanFallbackTest.java @@ -0,0 +1,85 @@ +/* + * 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 + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * 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. + */ + +/* + * @test + * @bug 8010285 + * @summary Test for the private MXBean interface fallback. + * It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic" + * system property must be set before c.s.j.m.MBeanAnalyzer has been loaded. + * @author Jaroslav Bachorik + * @run clean MXBeanFallbackTest + * @run build MXBeanFallbackTest + * @run main MXBeanFallbackTest + */ + +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +public class MXBeanFallbackTest { + public static void main(String[] args) throws Exception { + System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true"); + testPrivateMXBean("Private", new Private()); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static int failures = 0; + + private static interface PrivateMXBean { + public int[] getInts(); + } + + public static class Private implements PrivateMXBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + private static void testPrivateMXBean(String type, Object bean) throws Exception { + System.out.println(type + " MXBean test..."); + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=" + type); + try { + mbs.registerMBean(bean, on); + success("Private MXBean registered"); + } catch (NotCompliantMBeanException e) { + failure("Failed to register the private MXBean - " + + bean.getClass().getInterfaces()[0].getName()); + } + } + + private static void success(String what) { + System.out.println("OK: " + what); + } + + private static void failure(String what) { + System.out.println("FAILED: " + what); + failures++; + } +} diff --git a/test/javax/management/mxbean/MXBeanTest.java b/test/javax/management/mxbean/MXBeanTest.java index 7d1c79c9597da1d50a33383c4441b85c5cbece40..ecafe49adbb47d440e90535ba24dfc3e66394626 100644 --- a/test/javax/management/mxbean/MXBeanTest.java +++ b/test/javax/management/mxbean/MXBeanTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2008, 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 @@ -23,9 +23,10 @@ /* * @test - * @bug 6175517 6278707 6318827 6305746 6392303 6600709 + * @bug 6175517 6278707 6318827 6305746 6392303 6600709 8010285 * @summary General MXBean test. * @author Eamonn McManus + * @author Jaroslav Bachorik * @run clean MXBeanTest MerlinMXBean TigerMXBean * @run build MXBeanTest MerlinMXBean TigerMXBean * @run main MXBeanTest @@ -51,6 +52,7 @@ import javax.management.MBeanServer; import javax.management.MBeanServerConnection; import javax.management.MBeanServerFactory; import javax.management.MBeanServerInvocationHandler; +import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.StandardMBean; import javax.management.openmbean.ArrayType; @@ -75,6 +77,8 @@ public class MXBeanTest { testExplicitMXBean(); testSubclassMXBean(); testIndirectMXBean(); + testNonCompliantMXBean("Private", new Private()); + testNonCompliantMXBean("NonCompliant", new NonCompliant()); if (failures == 0) System.out.println("Test passed"); @@ -84,6 +88,39 @@ public class MXBeanTest { private static int failures = 0; + private static interface PrivateMXBean { + public int[] getInts(); + } + + public static class Private implements PrivateMXBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + public static interface NonCompliantMXBean { + public boolean getInt(); + public boolean isInt(); + public void setInt(int a); + public void setInt(long b); + } + + public static class NonCompliant implements NonCompliantMXBean { + public boolean getInt() { + return false; + } + + public boolean isInt() { + return true; + } + + public void setInt(int a) { + } + + public void setInt(long b) { + } + } + public static interface ExplicitMXBean { public int[] getInts(); } @@ -110,6 +147,19 @@ public class MXBeanTest { } } + private static void testNonCompliantMXBean(String type, Object bean) throws Exception { + System.out.println(type + " MXBean test..."); + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=" + type); + try { + mbs.registerMBean(bean, on); + failure(bean.getClass().getInterfaces()[0].getName() + " is not a compliant " + + "MXBean interface"); + } catch (NotCompliantMBeanException e) { + success("Non-compliant MXBean not registered"); + } + } + private static void testExplicitMXBean() throws Exception { System.out.println("Explicit MXBean test..."); MBeanServer mbs = MBeanServerFactory.newMBeanServer(); diff --git a/test/javax/management/proxy/JMXProxyFallbackTest.java b/test/javax/management/proxy/JMXProxyFallbackTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d1243593c110b9395812cdb2312543535bcafec8 --- /dev/null +++ b/test/javax/management/proxy/JMXProxyFallbackTest.java @@ -0,0 +1,100 @@ +/* + * 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. + * + * 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. + */ + +import javax.management.JMX; +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +/* + * @test + * @bug 8010285 + * @summary Tests the fallback for creating JMX proxies for private interfaces + * It needs to be a separate class because the "jdk.jmx.mbeans.allowNonPublic" + * system property must be set before c.s.j.m.MBeanAnalyzer has been loaded. + * @author Jaroslav Bachorik + * @run clean JMXProxyFallbackTest + * @run build JMXProxyFallbackTest + * @run main JMXProxyFallbackTest + */ +public class JMXProxyFallbackTest { + private static interface PrivateMBean { + public int[] getInts(); + } + + private static interface PrivateMXBean { + public int[] getInts(); + } + + public static class Private implements PrivateMXBean, PrivateMBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + private static int failures = 0; + + public static void main(String[] args) throws Exception { + System.setProperty("jdk.jmx.mbeans.allowNonPublic", "true"); + testPrivate(PrivateMBean.class); + testPrivate(PrivateMXBean.class); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static void fail(String msg) { + failures++; + System.out.println("FAIL: " + msg); + } + + private static void success(String msg) { + System.out.println("OK: " + msg); + } + + private static void testPrivate(Class iface) throws Exception { + try { + System.out.println("Creating a proxy for private M(X)Bean " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Proxy"); + + JMX.newMBeanProxy(mbs, on, iface); + success("Created a proxy for private M(X)Bean - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + fail("Proxy not created"); + } else { + throw e; + } + } + } +} diff --git a/test/javax/management/proxy/JMXProxyTest.java b/test/javax/management/proxy/JMXProxyTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0eb53cdebdb1ea03490eb9d63d168020a053bcc2 --- /dev/null +++ b/test/javax/management/proxy/JMXProxyTest.java @@ -0,0 +1,191 @@ +/* + * 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. + * + * 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. + */ + +import javax.management.JMX; +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; + +/* + * @test + * @bug 8010285 + * @summary Tests that javax.management.JMX creates proxies only for the + * compliant MBeans/MXBeans + * @author Jaroslav Bachorik + * @run clean JMXProxyTest + * @run build JMXProxyTest + * @run main JMXProxyTest + */ +public class JMXProxyTest { + private static interface PrivateMBean { + public int[] getInts(); + } + + private static interface PrivateMXBean { + public int[] getInts(); + } + + public static class Private implements PrivateMXBean, PrivateMBean { + public int[] getInts() { + return new int[]{1,2,3}; + } + } + + public static interface NonCompliantMBean { + public boolean getInt(); + public boolean isInt(); + public void setInt(int a); + public void setInt(long b); + } + + public static interface NonCompliantMXBean { + public boolean getInt(); + public boolean isInt(); + public void setInt(int a); + public void setInt(long b); + } + + public static class NonCompliant implements NonCompliantMXBean, NonCompliantMBean { + public boolean getInt() { + return false; + } + + public boolean isInt() { + return true; + } + + public void setInt(int a) { + } + + public void setInt(long b) { + } + } + + public static interface CompliantMBean { + public boolean isFlag(); + public int getInt(); + public void setInt(int value); + } + + public static interface CompliantMXBean { + public boolean isFlag(); + public int getInt(); + public void setInt(int value); + } + + public static class Compliant implements CompliantMXBean, CompliantMBean { + public boolean isFlag() { + return false; + } + + public int getInt() { + return 1; + } + + public void setInt(int value) { + } + } + + private static int failures = 0; + + public static void main(String[] args) throws Exception { + testCompliant(CompliantMBean.class, false); + testCompliant(CompliantMXBean.class, true); + testNonCompliant(PrivateMBean.class, false); + testNonCompliant(PrivateMXBean.class, true); + testNonCompliant(NonCompliantMBean.class, false); + testNonCompliant(NonCompliantMXBean.class, true); + + if (failures == 0) + System.out.println("Test passed"); + else + throw new Exception("TEST FAILURES: " + failures); + } + + private static void fail(String msg) { + failures++; + System.out.println("FAIL: " + msg); + } + + private static void success(String msg) { + System.out.println("OK: " + msg); + } + + private static void testNonCompliant(Class iface, boolean isMx) throws Exception { + try { + System.out.println("Creating a proxy for non-compliant " + + (isMx ? "MXBean" : "MBean") + " " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Proxy"); + + if (isMx) { + JMX.newMXBeanProxy(mbs, on, iface); + } else { + JMX.newMBeanProxy(mbs, on, iface); + } + fail("Created a proxy for non-compliant " + + (isMx ? "MXBean" : "MBean") + " - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + success("Proxy not created"); + } else { + throw e; + } + } + } + private static void testCompliant(Class iface, boolean isMx) throws Exception { + try { + System.out.println("Creating a proxy for compliant " + + (isMx ? "MXBean" : "MBean") + " " + + iface.getName() + " ..."); + + MBeanServer mbs = MBeanServerFactory.newMBeanServer(); + ObjectName on = new ObjectName("test:type=Proxy"); + + if (isMx) { + JMX.newMXBeanProxy(mbs, on, iface); + } else { + JMX.newMBeanProxy(mbs, on, iface); + } + success("Created a proxy for compliant " + + (isMx ? "MXBean" : "MBean") + " - " + iface.getName()); + } catch (Exception e) { + Throwable t = e; + while (t != null && !(t instanceof NotCompliantMBeanException)) { + t = t.getCause(); + } + if (t != null) { + fail("Proxy not created"); + } else { + throw e; + } + } + } +} diff --git a/test/sun/security/krb5/auto/SaslGSS.java b/test/sun/security/krb5/auto/SaslGSS.java index e497ab1a2966cfd12f8e5df16343506129a7b8cd..ec5419353088bb0e17f45cfa69293b97667f256c 100644 --- a/test/sun/security/krb5/auto/SaslGSS.java +++ b/test/sun/security/krb5/auto/SaslGSS.java @@ -23,7 +23,7 @@ /* * @test - * @bug 8012082 + * @bug 8012082 8019267 * @summary SASL: auth-conf negotiated, but unencrypted data is accepted, * reset to unencrypt * @compile -XDignore.symbol.file SaslGSS.java @@ -37,9 +37,16 @@ import javax.security.sasl.AuthorizeCallback; import javax.security.sasl.RealmCallback; import javax.security.sasl.Sasl; import javax.security.sasl.SaslServer; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.PrintStream; import java.util.HashMap; import java.util.Locale; +import java.util.logging.ConsoleHandler; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.Logger; + import org.ietf.jgss.*; import sun.security.jgss.GSSUtil; @@ -79,14 +86,28 @@ public class SaslGSS { } }); - // Handshake + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + PrintStream oldErr = System.err; + System.setErr(new PrintStream(bout)); + + Logger.getLogger("javax.security.sasl").setLevel(Level.ALL); + Handler h = new ConsoleHandler(); + h.setLevel(Level.ALL); + Logger.getLogger("javax.security.sasl").addHandler(h); + byte[] token = new byte[0]; - token = sc.initSecContext(token, 0, token.length); - token = ss.evaluateResponse(token); - token = sc.unwrap(token, 0, token.length, new MessageProp(0, false)); - token[0] = (byte)(((token[0] & 4) != 0) ? 4 : 2); - token = sc.wrap(token, 0, token.length, new MessageProp(0, false)); - ss.evaluateResponse(token); + + try { + // Handshake + token = sc.initSecContext(token, 0, token.length); + token = ss.evaluateResponse(token); + token = sc.unwrap(token, 0, token.length, new MessageProp(0, false)); + token[0] = (byte)(((token[0] & 4) != 0) ? 4 : 2); + token = sc.wrap(token, 0, token.length, new MessageProp(0, false)); + ss.evaluateResponse(token); + } finally { + System.setErr(oldErr); + } // Talk // 1. Client sends a auth-int message @@ -102,5 +123,15 @@ public class SaslGSS { if (!qop.getPrivacy()) { throw new Exception(); } + + for (String s: bout.toString().split("\\n")) { + if (s.contains("KRB5SRV04") && s.contains("NULL")) { + return; + } + } + System.out.println("======================="); + System.out.println(bout.toString()); + System.out.println("======================="); + throw new Exception("Haven't seen KRB5SRV04 with NULL"); } } diff --git a/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java b/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java index 81309213b351fda968e7082d0466a5c5649dfc36..9d6f62a8a1c237c6d749c99ee79abc14f944c899 100644 --- a/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java +++ b/test/sun/security/pkcs11/Signature/TestRSAKeyLength.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -36,7 +36,7 @@ public class TestRSAKeyLength extends PKCS11Test { main(new TestRSAKeyLength()); } public void main(Provider p) throws Exception { - boolean isValidKeyLength[] = { true, true, false, false }; + boolean isValidKeyLength[] = { true, true, true, false, false }; String algos[] = { "SHA1withRSA", "SHA224withRSA", "SHA256withRSA", "SHA384withRSA", "SHA512withRSA" }; KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", p); @@ -45,6 +45,10 @@ public class TestRSAKeyLength extends PKCS11Test { PrivateKey privKey = kp.getPrivate(); PublicKey pubKey = kp.getPublic(); + if (algos.length != isValidKeyLength.length) { + throw new Exception("Internal Error: number of test algos" + + " and results length mismatch!"); + } for (int i = 0; i < algos.length; i++) { Signature sig = Signature.getInstance(algos[i], p); System.out.println("Testing RSA signature " + algos[i]);

    unicast