1 /*
   2  * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import sun.invoke.util.Wrapper;
  29 import java.lang.ref.WeakReference;
  30 import java.lang.ref.Reference;
  31 import java.lang.ref.ReferenceQueue;
  32 import java.util.Arrays;
  33 import java.util.Collections;
  34 import java.util.List;
  35 import java.util.Objects;
  36 import java.util.StringJoiner;
  37 import java.util.concurrent.ConcurrentMap;
  38 import java.util.concurrent.ConcurrentHashMap;
  39 import sun.invoke.util.BytecodeDescriptor;
  40 import static java.lang.invoke.MethodHandleStatics.*;
  41 import sun.invoke.util.VerifyType;
  42 
  43 /**
  44  * A method type represents the arguments and return type accepted and
  45  * returned by a method handle, or the arguments and return type passed
  46  * and expected  by a method handle caller.  Method types must be properly
  47  * matched between a method handle and all its callers,
  48  * and the JVM's operations enforce this matching at, specifically
  49  * during calls to {@link MethodHandle#invokeExact MethodHandle.invokeExact}
  50  * and {@link MethodHandle#invoke MethodHandle.invoke}, and during execution
  51  * of {@code invokedynamic} instructions.
  52  * <p>
  53  * The structure is a return type accompanied by any number of parameter types.
  54  * The types (primitive, {@code void}, and reference) are represented by {@link Class} objects.
  55  * (For ease of exposition, we treat {@code void} as if it were a type.
  56  * In fact, it denotes the absence of a return type.)
  57  * <p>
  58  * All instances of {@code MethodType} are immutable.
  59  * Two instances are completely interchangeable if they compare equal.
  60  * Equality depends on pairwise correspondence of the return and parameter types and on nothing else.
  61  * <p>
  62  * This type can be created only by factory methods.
  63  * All factory methods may cache values, though caching is not guaranteed.
  64  * Some factory methods are static, while others are virtual methods which
  65  * modify precursor method types, e.g., by changing a selected parameter.
  66  * <p>
  67  * Factory methods which operate on groups of parameter types
  68  * are systematically presented in two versions, so that both Java arrays and
  69  * Java lists can be used to work with groups of parameter types.
  70  * The query methods {@code parameterArray} and {@code parameterList}
  71  * also provide a choice between arrays and lists.
  72  * <p>
  73  * {@code MethodType} objects are sometimes derived from bytecode instructions
  74  * such as {@code invokedynamic}, specifically from the type descriptor strings associated
  75  * with the instructions in a class file's constant pool.
  76  * <p>
  77  * Like classes and strings, method types can also be represented directly
  78  * in a class file's constant pool as constants.
  79  * A method type may be loaded by an {@code ldc} instruction which refers
  80  * to a suitable {@code CONSTANT_MethodType} constant pool entry.
  81  * The entry refers to a {@code CONSTANT_Utf8} spelling for the descriptor string.
  82  * (For full details on method type constants,
  83  * see sections 4.4.8 and 5.4.3.5 of the Java Virtual Machine Specification.)
  84  * <p>
  85  * When the JVM materializes a {@code MethodType} from a descriptor string,
  86  * all classes named in the descriptor must be accessible, and will be loaded.
  87  * (But the classes need not be initialized, as is the case with a {@code CONSTANT_Class}.)
  88  * This loading may occur at any time before the {@code MethodType} object is first derived.
  89  * @author John Rose, JSR 292 EG
  90  */
  91 public final
  92 class MethodType implements java.io.Serializable {
  93     private static final long serialVersionUID = 292L;  // {rtype, {ptype...}}
  94 
  95     // The rtype and ptypes fields define the structural identity of the method type:
  96     private final Class<?>   rtype;
  97     private final Class<?>[] ptypes;
  98 
  99     // The remaining fields are caches of various sorts:
 100     private @Stable MethodTypeForm form; // erased form, plus cached data about primitives
 101     private @Stable MethodType wrapAlt;  // alternative wrapped/unwrapped version
 102     private @Stable Invokers invokers;   // cache of handy higher-order adapters
 103     private @Stable String methodDescriptor;  // cache for toMethodDescriptorString
 104 
 105     /**
 106      * Check the given parameters for validity and store them into the final fields.
 107      */
 108     private MethodType(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
 109         checkRtype(rtype);
 110         checkPtypes(ptypes);
 111         this.rtype = rtype;
 112         // defensively copy the array passed in by the user
 113         this.ptypes = trusted ? ptypes : Arrays.copyOf(ptypes, ptypes.length);
 114     }
 115 
 116     /**
 117      * Construct a temporary unchecked instance of MethodType for use only as a key to the intern table.
 118      * Does not check the given parameters for validity, and must be discarded after it is used as a searching key.
 119      * The parameters are reversed for this constructor, so that is is not accidentally used.
 120      */
 121     private MethodType(Class<?>[] ptypes, Class<?> rtype) {
 122         this.rtype = rtype;
 123         this.ptypes = ptypes;
 124     }
 125 
 126     /*trusted*/ MethodTypeForm form() { return form; }
 127     /*trusted*/ Class<?> rtype() { return rtype; }
 128     /*trusted*/ Class<?>[] ptypes() { return ptypes; }
 129 
 130     void setForm(MethodTypeForm f) { form = f; }
 131 
 132     /** This number, mandated by the JVM spec as 255,
 133      *  is the maximum number of <em>slots</em>
 134      *  that any Java method can receive in its argument list.
 135      *  It limits both JVM signatures and method type objects.
 136      *  The longest possible invocation will look like
 137      *  {@code staticMethod(arg1, arg2, ..., arg255)} or
 138      *  {@code x.virtualMethod(arg1, arg2, ..., arg254)}.
 139      */
 140     /*non-public*/ static final int MAX_JVM_ARITY = 255;  // this is mandated by the JVM spec.
 141 
 142     /** This number is the maximum arity of a method handle, 254.
 143      *  It is derived from the absolute JVM-imposed arity by subtracting one,
 144      *  which is the slot occupied by the method handle itself at the
 145      *  beginning of the argument list used to invoke the method handle.
 146      *  The longest possible invocation will look like
 147      *  {@code mh.invoke(arg1, arg2, ..., arg254)}.
 148      */
 149     // Issue:  Should we allow MH.invokeWithArguments to go to the full 255?
 150     /*non-public*/ static final int MAX_MH_ARITY = MAX_JVM_ARITY-1;  // deduct one for mh receiver
 151 
 152     /** This number is the maximum arity of a method handle invoker, 253.
 153      *  It is derived from the absolute JVM-imposed arity by subtracting two,
 154      *  which are the slots occupied by invoke method handle, and the
 155      *  target method handle, which are both at the beginning of the argument
 156      *  list used to invoke the target method handle.
 157      *  The longest possible invocation will look like
 158      *  {@code invokermh.invoke(targetmh, arg1, arg2, ..., arg253)}.
 159      */
 160     /*non-public*/ static final int MAX_MH_INVOKER_ARITY = MAX_MH_ARITY-1;  // deduct one more for invoker
 161 
 162     private static void checkRtype(Class<?> rtype) {
 163         Objects.requireNonNull(rtype);
 164     }
 165     private static void checkPtype(Class<?> ptype) {
 166         Objects.requireNonNull(ptype);
 167         if (ptype == void.class)
 168             throw newIllegalArgumentException("parameter type cannot be void");
 169     }
 170     /** Return number of extra slots (count of long/double args). */
 171     private static int checkPtypes(Class<?>[] ptypes) {
 172         int slots = 0;
 173         for (Class<?> ptype : ptypes) {
 174             checkPtype(ptype);
 175             if (ptype == double.class || ptype == long.class) {
 176                 slots++;
 177             }
 178         }
 179         checkSlotCount(ptypes.length + slots);
 180         return slots;
 181     }
 182     static void checkSlotCount(int count) {
 183         assert((MAX_JVM_ARITY & (MAX_JVM_ARITY+1)) == 0);
 184         // MAX_JVM_ARITY must be power of 2 minus 1 for following code trick to work:
 185         if ((count & MAX_JVM_ARITY) != count)
 186             throw newIllegalArgumentException("bad parameter count "+count);
 187     }
 188     private static IndexOutOfBoundsException newIndexOutOfBoundsException(Object num) {
 189         if (num instanceof Integer)  num = "bad index: "+num;
 190         return new IndexOutOfBoundsException(num.toString());
 191     }
 192 
 193     static final ConcurrentWeakInternSet<MethodType> internTable = new ConcurrentWeakInternSet<>();
 194 
 195     static final Class<?>[] NO_PTYPES = {};
 196 
 197     /**
 198      * Finds or creates an instance of the given method type.
 199      * @param rtype  the return type
 200      * @param ptypes the parameter types
 201      * @return a method type with the given components
 202      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 203      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 204      */
 205     public static
 206     MethodType methodType(Class<?> rtype, Class<?>[] ptypes) {
 207         return makeImpl(rtype, ptypes, false);
 208     }
 209 
 210     /**
 211      * Finds or creates a method type with the given components.
 212      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 213      * @param rtype  the return type
 214      * @param ptypes the parameter types
 215      * @return a method type with the given components
 216      * @throws NullPointerException if {@code rtype} or {@code ptypes} or any element of {@code ptypes} is null
 217      * @throws IllegalArgumentException if any element of {@code ptypes} is {@code void.class}
 218      */
 219     public static
 220     MethodType methodType(Class<?> rtype, List<Class<?>> ptypes) {
 221         boolean notrust = false;  // random List impl. could return evil ptypes array
 222         return makeImpl(rtype, listToArray(ptypes), notrust);
 223     }
 224 
 225     private static Class<?>[] listToArray(List<Class<?>> ptypes) {
 226         // sanity check the size before the toArray call, since size might be huge
 227         checkSlotCount(ptypes.size());
 228         return ptypes.toArray(NO_PTYPES);
 229     }
 230 
 231     /**
 232      * Finds or creates a method type with the given components.
 233      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 234      * The leading parameter type is prepended to the remaining array.
 235      * @param rtype  the return type
 236      * @param ptype0 the first parameter type
 237      * @param ptypes the remaining parameter types
 238      * @return a method type with the given components
 239      * @throws NullPointerException if {@code rtype} or {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is null
 240      * @throws IllegalArgumentException if {@code ptype0} or {@code ptypes} or any element of {@code ptypes} is {@code void.class}
 241      */
 242     public static
 243     MethodType methodType(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes) {
 244         Class<?>[] ptypes1 = new Class<?>[1+ptypes.length];
 245         ptypes1[0] = ptype0;
 246         System.arraycopy(ptypes, 0, ptypes1, 1, ptypes.length);
 247         return makeImpl(rtype, ptypes1, true);
 248     }
 249 
 250     /**
 251      * Finds or creates a method type with the given components.
 252      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 253      * The resulting method has no parameter types.
 254      * @param rtype  the return type
 255      * @return a method type with the given return value
 256      * @throws NullPointerException if {@code rtype} is null
 257      */
 258     public static
 259     MethodType methodType(Class<?> rtype) {
 260         return makeImpl(rtype, NO_PTYPES, true);
 261     }
 262 
 263     /**
 264      * Finds or creates a method type with the given components.
 265      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 266      * The resulting method has the single given parameter type.
 267      * @param rtype  the return type
 268      * @param ptype0 the parameter type
 269      * @return a method type with the given return value and parameter type
 270      * @throws NullPointerException if {@code rtype} or {@code ptype0} is null
 271      * @throws IllegalArgumentException if {@code ptype0} is {@code void.class}
 272      */
 273     public static
 274     MethodType methodType(Class<?> rtype, Class<?> ptype0) {
 275         return makeImpl(rtype, new Class<?>[]{ ptype0 }, true);
 276     }
 277 
 278     /**
 279      * Finds or creates a method type with the given components.
 280      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 281      * The resulting method has the same parameter types as {@code ptypes},
 282      * and the specified return type.
 283      * @param rtype  the return type
 284      * @param ptypes the method type which supplies the parameter types
 285      * @return a method type with the given components
 286      * @throws NullPointerException if {@code rtype} or {@code ptypes} is null
 287      */
 288     public static
 289     MethodType methodType(Class<?> rtype, MethodType ptypes) {
 290         return makeImpl(rtype, ptypes.ptypes, true);
 291     }
 292 
 293     /**
 294      * Sole factory method to find or create an interned method type.
 295      * @param rtype desired return type
 296      * @param ptypes desired parameter types
 297      * @param trusted whether the ptypes can be used without cloning
 298      * @return the unique method type of the desired structure
 299      */
 300     /*trusted*/ static
 301     MethodType makeImpl(Class<?> rtype, Class<?>[] ptypes, boolean trusted) {
 302         MethodType mt = internTable.get(new MethodType(ptypes, rtype));
 303         if (mt != null)
 304             return mt;
 305         if (ptypes.length == 0) {
 306             ptypes = NO_PTYPES; trusted = true;
 307         }
 308         mt = new MethodType(rtype, ptypes, trusted);
 309         // promote the object to the Real Thing, and reprobe
 310         mt.form = MethodTypeForm.findForm(mt);
 311         return internTable.add(mt);
 312     }
 313     private static final MethodType[] objectOnlyTypes = new MethodType[20];
 314 
 315     /**
 316      * Finds or creates a method type whose components are {@code Object} with an optional trailing {@code Object[]} array.
 317      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 318      * All parameters and the return type will be {@code Object},
 319      * except the final array parameter if any, which will be {@code Object[]}.
 320      * @param objectArgCount number of parameters (excluding the final array parameter if any)
 321      * @param finalArray whether there will be a trailing array parameter, of type {@code Object[]}
 322      * @return a generally applicable method type, for all calls of the given fixed argument count and a collected array of further arguments
 323      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255 (or 254, if {@code finalArray} is true)
 324      * @see #genericMethodType(int)
 325      */
 326     public static
 327     MethodType genericMethodType(int objectArgCount, boolean finalArray) {
 328         MethodType mt;
 329         checkSlotCount(objectArgCount);
 330         int ivarargs = (!finalArray ? 0 : 1);
 331         int ootIndex = objectArgCount*2 + ivarargs;
 332         if (ootIndex < objectOnlyTypes.length) {
 333             mt = objectOnlyTypes[ootIndex];
 334             if (mt != null)  return mt;
 335         }
 336         Class<?>[] ptypes = new Class<?>[objectArgCount + ivarargs];
 337         Arrays.fill(ptypes, Object.class);
 338         if (ivarargs != 0)  ptypes[objectArgCount] = Object[].class;
 339         mt = makeImpl(Object.class, ptypes, true);
 340         if (ootIndex < objectOnlyTypes.length) {
 341             objectOnlyTypes[ootIndex] = mt;     // cache it here also!
 342         }
 343         return mt;
 344     }
 345 
 346     /**
 347      * Finds or creates a method type whose components are all {@code Object}.
 348      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 349      * All parameters and the return type will be Object.
 350      * @param objectArgCount number of parameters
 351      * @return a generally applicable method type, for all calls of the given argument count
 352      * @throws IllegalArgumentException if {@code objectArgCount} is negative or greater than 255
 353      * @see #genericMethodType(int, boolean)
 354      */
 355     public static
 356     MethodType genericMethodType(int objectArgCount) {
 357         return genericMethodType(objectArgCount, false);
 358     }
 359 
 360     /**
 361      * Finds or creates a method type with a single different parameter type.
 362      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 363      * @param num    the index (zero-based) of the parameter type to change
 364      * @param nptype a new parameter type to replace the old one with
 365      * @return the same type, except with the selected parameter changed
 366      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 367      * @throws IllegalArgumentException if {@code nptype} is {@code void.class}
 368      * @throws NullPointerException if {@code nptype} is null
 369      */
 370     public MethodType changeParameterType(int num, Class<?> nptype) {
 371         if (parameterType(num) == nptype)  return this;
 372         checkPtype(nptype);
 373         Class<?>[] nptypes = ptypes.clone();
 374         nptypes[num] = nptype;
 375         return makeImpl(rtype, nptypes, true);
 376     }
 377 
 378     /**
 379      * Finds or creates a method type with additional parameter types.
 380      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 381      * @param num    the position (zero-based) of the inserted parameter type(s)
 382      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 383      * @return the same type, except with the selected parameter(s) inserted
 384      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 385      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 386      *                                  or if the resulting method type would have more than 255 parameter slots
 387      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 388      */
 389     public MethodType insertParameterTypes(int num, Class<?>... ptypesToInsert) {
 390         int len = ptypes.length;
 391         if (num < 0 || num > len)
 392             throw newIndexOutOfBoundsException(num);
 393         int ins = checkPtypes(ptypesToInsert);
 394         checkSlotCount(parameterSlotCount() + ptypesToInsert.length + ins);
 395         int ilen = ptypesToInsert.length;
 396         if (ilen == 0)  return this;
 397         Class<?>[] nptypes = Arrays.copyOfRange(ptypes, 0, len+ilen);
 398         System.arraycopy(nptypes, num, nptypes, num+ilen, len-num);
 399         System.arraycopy(ptypesToInsert, 0, nptypes, num, ilen);
 400         return makeImpl(rtype, nptypes, true);
 401     }
 402 
 403     /**
 404      * Finds or creates a method type with additional parameter types.
 405      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 406      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 407      * @return the same type, except with the selected parameter(s) appended
 408      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 409      *                                  or if the resulting method type would have more than 255 parameter slots
 410      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 411      */
 412     public MethodType appendParameterTypes(Class<?>... ptypesToInsert) {
 413         return insertParameterTypes(parameterCount(), ptypesToInsert);
 414     }
 415 
 416     /**
 417      * Finds or creates a method type with additional parameter types.
 418      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 419      * @param num    the position (zero-based) of the inserted parameter type(s)
 420      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 421      * @return the same type, except with the selected parameter(s) inserted
 422      * @throws IndexOutOfBoundsException if {@code num} is negative or greater than {@code parameterCount()}
 423      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 424      *                                  or if the resulting method type would have more than 255 parameter slots
 425      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 426      */
 427     public MethodType insertParameterTypes(int num, List<Class<?>> ptypesToInsert) {
 428         return insertParameterTypes(num, listToArray(ptypesToInsert));
 429     }
 430 
 431     /**
 432      * Finds or creates a method type with additional parameter types.
 433      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 434      * @param ptypesToInsert zero or more new parameter types to insert after the end of the parameter list
 435      * @return the same type, except with the selected parameter(s) appended
 436      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 437      *                                  or if the resulting method type would have more than 255 parameter slots
 438      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 439      */
 440     public MethodType appendParameterTypes(List<Class<?>> ptypesToInsert) {
 441         return insertParameterTypes(parameterCount(), ptypesToInsert);
 442     }
 443 
 444      /**
 445      * Finds or creates a method type with modified parameter types.
 446      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 447      * @param start  the position (zero-based) of the first replaced parameter type(s)
 448      * @param end    the position (zero-based) after the last replaced parameter type(s)
 449      * @param ptypesToInsert zero or more new parameter types to insert into the parameter list
 450      * @return the same type, except with the selected parameter(s) replaced
 451      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 452      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 453      *                                  or if {@code start} is greater than {@code end}
 454      * @throws IllegalArgumentException if any element of {@code ptypesToInsert} is {@code void.class}
 455      *                                  or if the resulting method type would have more than 255 parameter slots
 456      * @throws NullPointerException if {@code ptypesToInsert} or any of its elements is null
 457      */
 458     /*non-public*/ MethodType replaceParameterTypes(int start, int end, Class<?>... ptypesToInsert) {
 459         if (start == end)
 460             return insertParameterTypes(start, ptypesToInsert);
 461         int len = ptypes.length;
 462         if (!(0 <= start && start <= end && end <= len))
 463             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 464         int ilen = ptypesToInsert.length;
 465         if (ilen == 0)
 466             return dropParameterTypes(start, end);
 467         return dropParameterTypes(start, end).insertParameterTypes(start, ptypesToInsert);
 468     }
 469 
 470     /** Replace the last arrayLength parameter types with the component type of arrayType.
 471      * @param arrayType any array type
 472      * @param arrayLength the number of parameter types to change
 473      * @return the resulting type
 474      */
 475     /*non-public*/ MethodType asSpreaderType(Class<?> arrayType, int arrayLength) {
 476         assert(parameterCount() >= arrayLength);
 477         int spreadPos = ptypes.length - arrayLength;
 478         if (arrayLength == 0)  return this;  // nothing to change
 479         if (arrayType == Object[].class) {
 480             if (isGeneric())  return this;  // nothing to change
 481             if (spreadPos == 0) {
 482                 // no leading arguments to preserve; go generic
 483                 MethodType res = genericMethodType(arrayLength);
 484                 if (rtype != Object.class) {
 485                     res = res.changeReturnType(rtype);
 486                 }
 487                 return res;
 488             }
 489         }
 490         Class<?> elemType = arrayType.getComponentType();
 491         assert(elemType != null);
 492         for (int i = spreadPos; i < ptypes.length; i++) {
 493             if (ptypes[i] != elemType) {
 494                 Class<?>[] fixedPtypes = ptypes.clone();
 495                 Arrays.fill(fixedPtypes, i, ptypes.length, elemType);
 496                 return methodType(rtype, fixedPtypes);
 497             }
 498         }
 499         return this;  // arguments check out; no change
 500     }
 501 
 502     /** Return the leading parameter type, which must exist and be a reference.
 503      *  @return the leading parameter type, after error checks
 504      */
 505     /*non-public*/ Class<?> leadingReferenceParameter() {
 506         Class<?> ptype;
 507         if (ptypes.length == 0 ||
 508             (ptype = ptypes[0]).isPrimitive())
 509             throw newIllegalArgumentException("no leading reference parameter");
 510         return ptype;
 511     }
 512 
 513     /**
 514      * Finds or creates a method type with some parameter types omitted.
 515      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 516      * @param start  the index (zero-based) of the first parameter type to remove
 517      * @param end    the index (greater than {@code start}) of the first parameter type after not to remove
 518      * @return the same type, except with the selected parameter(s) removed
 519      * @throws IndexOutOfBoundsException if {@code start} is negative or greater than {@code parameterCount()}
 520      *                                  or if {@code end} is negative or greater than {@code parameterCount()}
 521      *                                  or if {@code start} is greater than {@code end}
 522      */
 523     public MethodType dropParameterTypes(int start, int end) {
 524         int len = ptypes.length;
 525         if (!(0 <= start && start <= end && end <= len))
 526             throw newIndexOutOfBoundsException("start="+start+" end="+end);
 527         if (start == end)  return this;
 528         Class<?>[] nptypes;
 529         if (start == 0) {
 530             if (end == len) {
 531                 // drop all parameters
 532                 nptypes = NO_PTYPES;
 533             } else {
 534                 // drop initial parameter(s)
 535                 nptypes = Arrays.copyOfRange(ptypes, end, len);
 536             }
 537         } else {
 538             if (end == len) {
 539                 // drop trailing parameter(s)
 540                 nptypes = Arrays.copyOfRange(ptypes, 0, start);
 541             } else {
 542                 int tail = len - end;
 543                 nptypes = Arrays.copyOfRange(ptypes, 0, start + tail);
 544                 System.arraycopy(ptypes, end, nptypes, start, tail);
 545             }
 546         }
 547         return makeImpl(rtype, nptypes, true);
 548     }
 549 
 550     /**
 551      * Finds or creates a method type with a different return type.
 552      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 553      * @param nrtype a return parameter type to replace the old one with
 554      * @return the same type, except with the return type change
 555      * @throws NullPointerException if {@code nrtype} is null
 556      */
 557     public MethodType changeReturnType(Class<?> nrtype) {
 558         if (returnType() == nrtype)  return this;
 559         return makeImpl(nrtype, ptypes, true);
 560     }
 561 
 562     /**
 563      * Reports if this type contains a primitive argument or return value.
 564      * The return type {@code void} counts as a primitive.
 565      * @return true if any of the types are primitives
 566      */
 567     public boolean hasPrimitives() {
 568         return form.hasPrimitives();
 569     }
 570 
 571     /**
 572      * Reports if this type contains a wrapper argument or return value.
 573      * Wrappers are types which box primitive values, such as {@link Integer}.
 574      * The reference type {@code java.lang.Void} counts as a wrapper,
 575      * if it occurs as a return type.
 576      * @return true if any of the types are wrappers
 577      */
 578     public boolean hasWrappers() {
 579         return unwrap() != this;
 580     }
 581 
 582     /**
 583      * Erases all reference types to {@code Object}.
 584      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 585      * All primitive types (including {@code void}) will remain unchanged.
 586      * @return a version of the original type with all reference types replaced
 587      */
 588     public MethodType erase() {
 589         return form.erasedType();
 590     }
 591 
 592     /**
 593      * Erases all reference types to {@code Object}, and all subword types to {@code int}.
 594      * This is the reduced type polymorphism used by private methods
 595      * such as {@link MethodHandle#invokeBasic invokeBasic}.
 596      * @return a version of the original type with all reference and subword types replaced
 597      */
 598     /*non-public*/ MethodType basicType() {
 599         return form.basicType();
 600     }
 601 
 602     /**
 603      * @return a version of the original type with MethodHandle prepended as the first argument
 604      */
 605     /*non-public*/ MethodType invokerType() {
 606         return insertParameterTypes(0, MethodHandle.class);
 607     }
 608 
 609     /**
 610      * Converts all types, both reference and primitive, to {@code Object}.
 611      * Convenience method for {@link #genericMethodType(int) genericMethodType}.
 612      * The expression {@code type.wrap().erase()} produces the same value
 613      * as {@code type.generic()}.
 614      * @return a version of the original type with all types replaced
 615      */
 616     public MethodType generic() {
 617         return genericMethodType(parameterCount());
 618     }
 619 
 620     /*non-public*/ boolean isGeneric() {
 621         return this == erase() && !hasPrimitives();
 622     }
 623 
 624     /**
 625      * Converts all primitive types to their corresponding wrapper types.
 626      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 627      * All reference types (including wrapper types) will remain unchanged.
 628      * A {@code void} return type is changed to the type {@code java.lang.Void}.
 629      * The expression {@code type.wrap().erase()} produces the same value
 630      * as {@code type.generic()}.
 631      * @return a version of the original type with all primitive types replaced
 632      */
 633     public MethodType wrap() {
 634         return hasPrimitives() ? wrapWithPrims(this) : this;
 635     }
 636 
 637     /**
 638      * Converts all wrapper types to their corresponding primitive types.
 639      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 640      * All primitive types (including {@code void}) will remain unchanged.
 641      * A return type of {@code java.lang.Void} is changed to {@code void}.
 642      * @return a version of the original type with all wrapper types replaced
 643      */
 644     public MethodType unwrap() {
 645         MethodType noprims = !hasPrimitives() ? this : wrapWithPrims(this);
 646         return unwrapWithNoPrims(noprims);
 647     }
 648 
 649     private static MethodType wrapWithPrims(MethodType pt) {
 650         assert(pt.hasPrimitives());
 651         MethodType wt = pt.wrapAlt;
 652         if (wt == null) {
 653             // fill in lazily
 654             wt = MethodTypeForm.canonicalize(pt, MethodTypeForm.WRAP, MethodTypeForm.WRAP);
 655             assert(wt != null);
 656             pt.wrapAlt = wt;
 657         }
 658         return wt;
 659     }
 660 
 661     private static MethodType unwrapWithNoPrims(MethodType wt) {
 662         assert(!wt.hasPrimitives());
 663         MethodType uwt = wt.wrapAlt;
 664         if (uwt == null) {
 665             // fill in lazily
 666             uwt = MethodTypeForm.canonicalize(wt, MethodTypeForm.UNWRAP, MethodTypeForm.UNWRAP);
 667             if (uwt == null)
 668                 uwt = wt;    // type has no wrappers or prims at all
 669             wt.wrapAlt = uwt;
 670         }
 671         return uwt;
 672     }
 673 
 674     /**
 675      * Returns the parameter type at the specified index, within this method type.
 676      * @param num the index (zero-based) of the desired parameter type
 677      * @return the selected parameter type
 678      * @throws IndexOutOfBoundsException if {@code num} is not a valid index into {@code parameterArray()}
 679      */
 680     public Class<?> parameterType(int num) {
 681         return ptypes[num];
 682     }
 683     /**
 684      * Returns the number of parameter types in this method type.
 685      * @return the number of parameter types
 686      */
 687     public int parameterCount() {
 688         return ptypes.length;
 689     }
 690     /**
 691      * Returns the return type of this method type.
 692      * @return the return type
 693      */
 694     public Class<?> returnType() {
 695         return rtype;
 696     }
 697 
 698     /**
 699      * Presents the parameter types as a list (a convenience method).
 700      * The list will be immutable.
 701      * @return the parameter types (as an immutable list)
 702      */
 703     public List<Class<?>> parameterList() {
 704         return Collections.unmodifiableList(Arrays.asList(ptypes));
 705     }
 706 
 707     /*non-public*/ Class<?> lastParameterType() {
 708         int len = ptypes.length;
 709         return len == 0 ? void.class : ptypes[len-1];
 710     }
 711 
 712     /**
 713      * Presents the parameter types as an array (a convenience method).
 714      * Changes to the array will not result in changes to the type.
 715      * @return the parameter types (as a fresh copy if necessary)
 716      */
 717     public Class<?>[] parameterArray() {
 718         return ptypes.clone();
 719     }
 720 
 721     /**
 722      * Compares the specified object with this type for equality.
 723      * That is, it returns <tt>true</tt> if and only if the specified object
 724      * is also a method type with exactly the same parameters and return type.
 725      * @param x object to compare
 726      * @see Object#equals(Object)
 727      */
 728     @Override
 729     public boolean equals(Object x) {
 730         return this == x || x instanceof MethodType && equals((MethodType)x);
 731     }
 732 
 733     private boolean equals(MethodType that) {
 734         return this.rtype == that.rtype
 735             && Arrays.equals(this.ptypes, that.ptypes);
 736     }
 737 
 738     /**
 739      * Returns the hash code value for this method type.
 740      * It is defined to be the same as the hashcode of a List
 741      * whose elements are the return type followed by the
 742      * parameter types.
 743      * @return the hash code value for this method type
 744      * @see Object#hashCode()
 745      * @see #equals(Object)
 746      * @see List#hashCode()
 747      */
 748     @Override
 749     public int hashCode() {
 750       int hashCode = 31 + rtype.hashCode();
 751       for (Class<?> ptype : ptypes)
 752           hashCode = 31*hashCode + ptype.hashCode();
 753       return hashCode;
 754     }
 755 
 756     /**
 757      * Returns a string representation of the method type,
 758      * of the form {@code "(PT0,PT1...)RT"}.
 759      * The string representation of a method type is a
 760      * parenthesis enclosed, comma separated list of type names,
 761      * followed immediately by the return type.
 762      * <p>
 763      * Each type is represented by its
 764      * {@link java.lang.Class#getSimpleName simple name}.
 765      */
 766     @Override
 767     public String toString() {
 768         StringJoiner sj = new StringJoiner(",", "(",
 769                 ")" + rtype.getSimpleName());
 770         for (int i = 0; i < ptypes.length; i++) {
 771             sj.add(ptypes[i].getSimpleName());
 772         }
 773         return sj.toString();
 774     }
 775 
 776 
 777     /*non-public*/
 778     boolean isViewableAs(MethodType newType) {
 779         if (!VerifyType.isNullConversion(returnType(), newType.returnType(), true))
 780             return false;
 781         int argc = parameterCount();
 782         if (argc != newType.parameterCount())
 783             return false;
 784         for (int i = 0; i < argc; i++) {
 785             if (!VerifyType.isNullConversion(newType.parameterType(i), parameterType(i), true))
 786                 return false;
 787         }
 788         return true;
 789     }
 790     /*non-public*/
 791     boolean isCastableTo(MethodType newType) {
 792         int argc = parameterCount();
 793         if (argc != newType.parameterCount())
 794             return false;
 795         return true;
 796     }
 797     /*non-public*/
 798     boolean isConvertibleTo(MethodType newType) {
 799         if (!canConvert(returnType(), newType.returnType()))
 800             return false;
 801         int argc = parameterCount();
 802         if (argc != newType.parameterCount())
 803             return false;
 804         for (int i = 0; i < argc; i++) {
 805             if (!canConvert(newType.parameterType(i), parameterType(i)))
 806                 return false;
 807         }
 808         return true;
 809     }
 810     /*non-public*/
 811     static boolean canConvert(Class<?> src, Class<?> dst) {
 812         // short-circuit a few cases:
 813         if (src == dst || dst == Object.class)  return true;
 814         // the remainder of this logic is documented in MethodHandle.asType
 815         if (src.isPrimitive()) {
 816             // can force void to an explicit null, a la reflect.Method.invoke
 817             // can also force void to a primitive zero, by analogy
 818             if (src == void.class)  return true;  //or !dst.isPrimitive()?
 819             Wrapper sw = Wrapper.forPrimitiveType(src);
 820             if (dst.isPrimitive()) {
 821                 // P->P must widen
 822                 return Wrapper.forPrimitiveType(dst).isConvertibleFrom(sw);
 823             } else {
 824                 // P->R must box and widen
 825                 return dst.isAssignableFrom(sw.wrapperType());
 826             }
 827         } else if (dst.isPrimitive()) {
 828             // any value can be dropped
 829             if (dst == void.class)  return true;
 830             Wrapper dw = Wrapper.forPrimitiveType(dst);
 831             // R->P must be able to unbox (from a dynamically chosen type) and widen
 832             // For example:
 833             //   Byte/Number/Comparable/Object -> dw:Byte -> byte.
 834             //   Character/Comparable/Object -> dw:Character -> char
 835             //   Boolean/Comparable/Object -> dw:Boolean -> boolean
 836             // This means that dw must be cast-compatible with src.
 837             if (src.isAssignableFrom(dw.wrapperType())) {
 838                 return true;
 839             }
 840             // The above does not work if the source reference is strongly typed
 841             // to a wrapper whose primitive must be widened.  For example:
 842             //   Byte -> unbox:byte -> short/int/long/float/double
 843             //   Character -> unbox:char -> int/long/float/double
 844             if (Wrapper.isWrapperType(src) &&
 845                 dw.isConvertibleFrom(Wrapper.forWrapperType(src))) {
 846                 // can unbox from src and then widen to dst
 847                 return true;
 848             }
 849             // We have already covered cases which arise due to runtime unboxing
 850             // of a reference type which covers several wrapper types:
 851             //   Object -> cast:Integer -> unbox:int -> long/float/double
 852             //   Serializable -> cast:Byte -> unbox:byte -> byte/short/int/long/float/double
 853             // An marginal case is Number -> dw:Character -> char, which would be OK if there were a
 854             // subclass of Number which wraps a value that can convert to char.
 855             // Since there is none, we don't need an extra check here to cover char or boolean.
 856             return false;
 857         } else {
 858             // R->R always works, since null is always valid dynamically
 859             return true;
 860         }
 861     }
 862 
 863     /// Queries which have to do with the bytecode architecture
 864 
 865     /** Reports the number of JVM stack slots required to invoke a method
 866      * of this type.  Note that (for historical reasons) the JVM requires
 867      * a second stack slot to pass long and double arguments.
 868      * So this method returns {@link #parameterCount() parameterCount} plus the
 869      * number of long and double parameters (if any).
 870      * <p>
 871      * This method is included for the benefit of applications that must
 872      * generate bytecodes that process method handles and invokedynamic.
 873      * @return the number of JVM stack slots for this type's parameters
 874      */
 875     /*non-public*/ int parameterSlotCount() {
 876         return form.parameterSlotCount();
 877     }
 878 
 879     /*non-public*/ Invokers invokers() {
 880         Invokers inv = invokers;
 881         if (inv != null)  return inv;
 882         invokers = inv = new Invokers(this);
 883         return inv;
 884     }
 885 
 886     /** Reports the number of JVM stack slots which carry all parameters including and after
 887      * the given position, which must be in the range of 0 to
 888      * {@code parameterCount} inclusive.  Successive parameters are
 889      * more shallowly stacked, and parameters are indexed in the bytecodes
 890      * according to their trailing edge.  Thus, to obtain the depth
 891      * in the outgoing call stack of parameter {@code N}, obtain
 892      * the {@code parameterSlotDepth} of its trailing edge
 893      * at position {@code N+1}.
 894      * <p>
 895      * Parameters of type {@code long} and {@code double} occupy
 896      * two stack slots (for historical reasons) and all others occupy one.
 897      * Therefore, the number returned is the number of arguments
 898      * <em>including</em> and <em>after</em> the given parameter,
 899      * <em>plus</em> the number of long or double arguments
 900      * at or after after the argument for the given parameter.
 901      * <p>
 902      * This method is included for the benefit of applications that must
 903      * generate bytecodes that process method handles and invokedynamic.
 904      * @param num an index (zero-based, inclusive) within the parameter types
 905      * @return the index of the (shallowest) JVM stack slot transmitting the
 906      *         given parameter
 907      * @throws IllegalArgumentException if {@code num} is negative or greater than {@code parameterCount()}
 908      */
 909     /*non-public*/ int parameterSlotDepth(int num) {
 910         if (num < 0 || num > ptypes.length)
 911             parameterType(num);  // force a range check
 912         return form.parameterToArgSlot(num-1);
 913     }
 914 
 915     /** Reports the number of JVM stack slots required to receive a return value
 916      * from a method of this type.
 917      * If the {@link #returnType() return type} is void, it will be zero,
 918      * else if the return type is long or double, it will be two, else one.
 919      * <p>
 920      * This method is included for the benefit of applications that must
 921      * generate bytecodes that process method handles and invokedynamic.
 922      * @return the number of JVM stack slots (0, 1, or 2) for this type's return value
 923      * Will be removed for PFD.
 924      */
 925     /*non-public*/ int returnSlotCount() {
 926         return form.returnSlotCount();
 927     }
 928 
 929     /**
 930      * Finds or creates an instance of a method type, given the spelling of its bytecode descriptor.
 931      * Convenience method for {@link #methodType(java.lang.Class, java.lang.Class[]) methodType}.
 932      * Any class or interface name embedded in the descriptor string
 933      * will be resolved by calling {@link ClassLoader#loadClass(java.lang.String)}
 934      * on the given loader (or if it is null, on the system class loader).
 935      * <p>
 936      * Note that it is possible to encounter method types which cannot be
 937      * constructed by this method, because their component types are
 938      * not all reachable from a common class loader.
 939      * <p>
 940      * This method is included for the benefit of applications that must
 941      * generate bytecodes that process method handles and {@code invokedynamic}.
 942      * @param descriptor a bytecode-level type descriptor string "(T...)T"
 943      * @param loader the class loader in which to look up the types
 944      * @return a method type matching the bytecode-level type descriptor
 945      * @throws NullPointerException if the string is null
 946      * @throws IllegalArgumentException if the string is not well-formed
 947      * @throws TypeNotPresentException if a named type cannot be found
 948      */
 949     public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
 950         throws IllegalArgumentException, TypeNotPresentException
 951     {
 952         if (!descriptor.startsWith("(") ||  // also generates NPE if needed
 953             descriptor.indexOf(')') < 0 ||
 954             descriptor.indexOf('.') >= 0)
 955             throw newIllegalArgumentException("not a method descriptor: "+descriptor);
 956         List<Class<?>> types = BytecodeDescriptor.parseMethod(descriptor, loader);
 957         Class<?> rtype = types.remove(types.size() - 1);
 958         checkSlotCount(types.size());
 959         Class<?>[] ptypes = listToArray(types);
 960         return makeImpl(rtype, ptypes, true);
 961     }
 962 
 963     /**
 964      * Produces a bytecode descriptor representation of the method type.
 965      * <p>
 966      * Note that this is not a strict inverse of {@link #fromMethodDescriptorString fromMethodDescriptorString}.
 967      * Two distinct classes which share a common name but have different class loaders
 968      * will appear identical when viewed within descriptor strings.
 969      * <p>
 970      * This method is included for the benefit of applications that must
 971      * generate bytecodes that process method handles and {@code invokedynamic}.
 972      * {@link #fromMethodDescriptorString(java.lang.String, java.lang.ClassLoader) fromMethodDescriptorString},
 973      * because the latter requires a suitable class loader argument.
 974      * @return the bytecode type descriptor representation
 975      */
 976     public String toMethodDescriptorString() {
 977         String desc = methodDescriptor;
 978         if (desc == null) {
 979             desc = BytecodeDescriptor.unparse(this);
 980             methodDescriptor = desc;
 981         }
 982         return desc;
 983     }
 984 
 985     /*non-public*/ static String toFieldDescriptorString(Class<?> cls) {
 986         return BytecodeDescriptor.unparse(cls);
 987     }
 988 
 989     /// Serialization.
 990 
 991     /**
 992      * There are no serializable fields for {@code MethodType}.
 993      */
 994     private static final java.io.ObjectStreamField[] serialPersistentFields = { };
 995 
 996     /**
 997      * Save the {@code MethodType} instance to a stream.
 998      *
 999      * @serialData
1000      * For portability, the serialized format does not refer to named fields.
1001      * Instead, the return type and parameter type arrays are written directly
1002      * from the {@code writeObject} method, using two calls to {@code s.writeObject}
1003      * as follows:
1004      * <blockquote><pre>{@code
1005 s.writeObject(this.returnType());
1006 s.writeObject(this.parameterArray());
1007      * }</pre></blockquote>
1008      * <p>
1009      * The deserialized field values are checked as if they were
1010      * provided to the factory method {@link #methodType(Class,Class[]) methodType}.
1011      * For example, null values, or {@code void} parameter types,
1012      * will lead to exceptions during deserialization.
1013      * @param s the stream to write the object to
1014      * @throws java.io.IOException if there is a problem writing the object
1015      */
1016     private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
1017         s.defaultWriteObject();  // requires serialPersistentFields to be an empty array
1018         s.writeObject(returnType());
1019         s.writeObject(parameterArray());
1020     }
1021 
1022     /**
1023      * Reconstitute the {@code MethodType} instance from a stream (that is,
1024      * deserialize it).
1025      * This instance is a scratch object with bogus final fields.
1026      * It provides the parameters to the factory method called by
1027      * {@link #readResolve readResolve}.
1028      * After that call it is discarded.
1029      * @param s the stream to read the object from
1030      * @throws java.io.IOException if there is a problem reading the object
1031      * @throws ClassNotFoundException if one of the component classes cannot be resolved
1032      * @see #MethodType()
1033      * @see #readResolve
1034      * @see #writeObject
1035      */
1036     private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
1037         s.defaultReadObject();  // requires serialPersistentFields to be an empty array
1038 
1039         Class<?>   returnType     = (Class<?>)   s.readObject();
1040         Class<?>[] parameterArray = (Class<?>[]) s.readObject();
1041 
1042         // Probably this object will never escape, but let's check
1043         // the field values now, just to be sure.
1044         checkRtype(returnType);
1045         checkPtypes(parameterArray);
1046 
1047         parameterArray = parameterArray.clone();  // make sure it is unshared
1048         MethodType_init(returnType, parameterArray);
1049     }
1050 
1051     /**
1052      * For serialization only.
1053      * Sets the final fields to null, pending {@code Unsafe.putObject}.
1054      */
1055     private MethodType() {
1056         this.rtype = null;
1057         this.ptypes = null;
1058     }
1059     private void MethodType_init(Class<?> rtype, Class<?>[] ptypes) {
1060         // In order to communicate these values to readResolve, we must
1061         // store them into the implementation-specific final fields.
1062         checkRtype(rtype);
1063         checkPtypes(ptypes);
1064         UNSAFE.putObject(this, rtypeOffset, rtype);
1065         UNSAFE.putObject(this, ptypesOffset, ptypes);
1066     }
1067 
1068     // Support for resetting final fields while deserializing
1069     private static final long rtypeOffset, ptypesOffset;
1070     static {
1071         try {
1072             rtypeOffset = UNSAFE.objectFieldOffset
1073                 (MethodType.class.getDeclaredField("rtype"));
1074             ptypesOffset = UNSAFE.objectFieldOffset
1075                 (MethodType.class.getDeclaredField("ptypes"));
1076         } catch (Exception ex) {
1077             throw new Error(ex);
1078         }
1079     }
1080 
1081     /**
1082      * Resolves and initializes a {@code MethodType} object
1083      * after serialization.
1084      * @return the fully initialized {@code MethodType} object
1085      */
1086     private Object readResolve() {
1087         // Do not use a trusted path for deserialization:
1088         //return makeImpl(rtype, ptypes, true);
1089         // Verify all operands, and make sure ptypes is unshared:
1090         return methodType(rtype, ptypes);
1091     }
1092 
1093     /**
1094      * Simple implementation of weak concurrent intern set.
1095      *
1096      * @param <T> interned type
1097      */
1098     private static class ConcurrentWeakInternSet<T> {
1099 
1100         private final ConcurrentMap<WeakEntry<T>, WeakEntry<T>> map;
1101         private final ReferenceQueue<T> stale;
1102 
1103         public ConcurrentWeakInternSet() {
1104             this.map = new ConcurrentHashMap<>();
1105             this.stale = new ReferenceQueue<>();
1106         }
1107 
1108         /**
1109          * Get the existing interned element.
1110          * This method returns null if no element is interned.
1111          *
1112          * @param elem element to look up
1113          * @return the interned element
1114          */
1115         public T get(T elem) {
1116             if (elem == null) throw new NullPointerException();
1117             expungeStaleElements();
1118 
1119             WeakEntry<T> value = map.get(new WeakEntry<>(elem));
1120             if (value != null) {
1121                 T res = value.get();
1122                 if (res != null) {
1123                     return res;
1124                 }
1125             }
1126             return null;
1127         }
1128 
1129         /**
1130          * Interns the element.
1131          * Always returns non-null element, matching the one in the intern set.
1132          * Under the race against another add(), it can return <i>different</i>
1133          * element, if another thread beats us to interning it.
1134          *
1135          * @param elem element to add
1136          * @return element that was actually added
1137          */
1138         public T add(T elem) {
1139             if (elem == null) throw new NullPointerException();
1140 
1141             // Playing double race here, and so spinloop is required.
1142             // First race is with two concurrent updaters.
1143             // Second race is with GC purging weak ref under our feet.
1144             // Hopefully, we almost always end up with a single pass.
1145             T interned;
1146             WeakEntry<T> e = new WeakEntry<>(elem, stale);
1147             do {
1148                 expungeStaleElements();
1149                 WeakEntry<T> exist = map.putIfAbsent(e, e);
1150                 interned = (exist == null) ? elem : exist.get();
1151             } while (interned == null);
1152             return interned;
1153         }
1154 
1155         private void expungeStaleElements() {
1156             Reference<? extends T> reference;
1157             while ((reference = stale.poll()) != null) {
1158                 map.remove(reference);
1159             }
1160         }
1161 
1162         private static class WeakEntry<T> extends WeakReference<T> {
1163 
1164             public final int hashcode;
1165 
1166             public WeakEntry(T key, ReferenceQueue<T> queue) {
1167                 super(key, queue);
1168                 hashcode = key.hashCode();
1169             }
1170 
1171             public WeakEntry(T key) {
1172                 super(key);
1173                 hashcode = key.hashCode();
1174             }
1175 
1176             @Override
1177             public boolean equals(Object obj) {
1178                 if (obj instanceof WeakEntry) {
1179                     Object that = ((WeakEntry) obj).get();
1180                     Object mine = get();
1181                     return (that == null || mine == null) ? (this == obj) : mine.equals(that);
1182                 }
1183                 return false;
1184             }
1185 
1186             @Override
1187             public int hashCode() {
1188                 return hashcode;
1189             }
1190 
1191         }
1192     }
1193 
1194 }