1 /*
   2  * Copyright (c) 2014, 2023, 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 java.lang.constant.ClassDesc;
  29 import java.lang.constant.Constable;
  30 import java.lang.constant.ConstantDesc;
  31 import java.lang.constant.ConstantDescs;
  32 import java.lang.constant.DirectMethodHandleDesc;
  33 import java.lang.constant.DynamicConstantDesc;
  34 import java.util.List;
  35 import java.util.Objects;
  36 import java.util.Optional;
  37 
  38 import jdk.internal.value.PrimitiveClass;
  39 import jdk.internal.vm.annotation.DontInline;
  40 import jdk.internal.vm.annotation.ForceInline;
  41 import jdk.internal.vm.annotation.IntrinsicCandidate;
  42 import jdk.internal.vm.annotation.Stable;
  43 
  44 import static java.lang.invoke.MethodHandleStatics.UNSAFE;
  45 
  46 /**
  47  * A VarHandle is a dynamically strongly typed reference to a variable, or to a
  48  * parametrically-defined family of variables, including static fields,
  49  * non-static fields, array elements, or components of an off-heap data
  50  * structure.  Access to such variables is supported under various
  51  * <em>access modes</em>, including plain read/write access, volatile
  52  * read/write access, and compare-and-set.
  53  *
  54  * <p>VarHandles are immutable and have no visible state.  VarHandles cannot be
  55  * subclassed by the user.
  56  *
  57  * <p>A VarHandle has:
  58  * <ul>
  59  * <li>a {@link #varType variable type} T, the type of every variable referenced
  60  * by this VarHandle; and
  61  * <li>a list of {@link #coordinateTypes coordinate types}
  62  * {@code CT1, CT2, ..., CTn}, the types of <em>coordinate expressions</em> that
  63  * jointly locate a variable referenced by this VarHandle.
  64  * </ul>
  65  * Variable and coordinate types may be primitive or reference, and are
  66  * represented by {@code Class} objects.  The list of coordinate types may be
  67  * empty.
  68  *
  69  * <p>Factory methods that produce or {@link java.lang.invoke.MethodHandles.Lookup
  70  * lookup} VarHandle instances document the supported variable type and the list
  71  * of coordinate types.
  72  *
  73  * <p>Each access mode is associated with one <em>access mode method</em>, a
  74  * <a href="MethodHandle.html#sigpoly">signature polymorphic</a> method named
  75  * for the access mode.  When an access mode method is invoked on a VarHandle
  76  * instance, the initial arguments to the invocation are coordinate expressions
  77  * that indicate in precisely which object the variable is to be accessed.
  78  * Trailing arguments to the invocation represent values of importance to the
  79  * access mode.  For example, the various compare-and-set or compare-and-exchange
  80  * access modes require two trailing arguments for the variable's expected value
  81  * and new value.
  82  *
  83  * <p>The arity and types of arguments to the invocation of an access mode
  84  * method are not checked statically.  Instead, each access mode method
  85  * specifies an {@link #accessModeType(AccessMode) access mode type},
  86  * represented as an instance of {@link MethodType}, that serves as a kind of
  87  * method signature against which the arguments are checked dynamically.  An
  88  * access mode type gives formal parameter types in terms of the coordinate
  89  * types of a VarHandle instance and the types for values of importance to the
  90  * access mode.  An access mode type also gives a return type, often in terms of
  91  * the variable type of a VarHandle instance.  When an access mode method is
  92  * invoked on a VarHandle instance, the symbolic type descriptor at the
  93  * call site, the run time types of arguments to the invocation, and the run
  94  * time type of the return value, must <a href="#invoke">match</a> the types
  95  * given in the access mode type.  A runtime exception will be thrown if the
  96  * match fails.
  97  *
  98  * For example, the access mode method {@link #compareAndSet} specifies that if
  99  * its receiver is a VarHandle instance with coordinate types
 100  * {@code CT1, ..., CTn} and variable type {@code T}, then its access mode type
 101  * is {@code (CT1 c1, ..., CTn cn, T expectedValue, T newValue)boolean}.
 102  * Suppose that a VarHandle instance can access array elements, and that its
 103  * coordinate types are {@code String[]} and {@code int} while its variable type
 104  * is {@code String}.  The access mode type for {@code compareAndSet} on this
 105  * VarHandle instance would be
 106  * {@code (String[] c1, int c2, String expectedValue, String newValue)boolean}.
 107  * Such a VarHandle instance may be produced by the
 108  * {@link MethodHandles#arrayElementVarHandle(Class) array factory method} and
 109  * access array elements as follows:
 110  * <pre> {@code
 111  * String[] sa = ...
 112  * VarHandle avh = MethodHandles.arrayElementVarHandle(String[].class);
 113  * boolean r = avh.compareAndSet(sa, 10, "expected", "new");
 114  * }</pre>
 115  *
 116  * <p>Access modes control atomicity and consistency properties.
 117  * <em>Plain</em> read ({@code get}) and write ({@code set})
 118  * accesses are guaranteed to be bitwise atomic only for references
 119  * and for primitive values of at most 32 bits, and impose no observable
 120  * ordering constraints with respect to threads other than the
 121  * executing thread. <em>Opaque</em> operations are bitwise atomic and
 122  * coherently ordered with respect to accesses to the same variable.
 123  * In addition to obeying Opaque properties, <em>Acquire</em> mode
 124  * reads and their subsequent accesses are ordered after matching
 125  * <em>Release</em> mode writes and their previous accesses.  In
 126  * addition to obeying Acquire and Release properties, all
 127  * <em>Volatile</em> operations are totally ordered with respect to
 128  * each other.
 129  *
 130  * <p>Access modes are grouped into the following categories:
 131  * <ul>
 132  * <li>read access modes that get the value of a variable under specified
 133  * memory ordering effects.
 134  * The set of corresponding access mode methods belonging to this group
 135  * consists of the methods
 136  * {@link #get get},
 137  * {@link #getVolatile getVolatile},
 138  * {@link #getAcquire getAcquire},
 139  * {@link #getOpaque getOpaque}.
 140  * <li>write access modes that set the value of a variable under specified
 141  * memory ordering effects.
 142  * The set of corresponding access mode methods belonging to this group
 143  * consists of the methods
 144  * {@link #set set},
 145  * {@link #setVolatile setVolatile},
 146  * {@link #setRelease setRelease},
 147  * {@link #setOpaque setOpaque}.
 148  * <li>atomic update access modes that, for example, atomically compare and set
 149  * the value of a variable under specified memory ordering effects.
 150  * The set of corresponding access mode methods belonging to this group
 151  * consists of the methods
 152  * {@link #compareAndSet compareAndSet},
 153  * {@link #weakCompareAndSetPlain weakCompareAndSetPlain},
 154  * {@link #weakCompareAndSet weakCompareAndSet},
 155  * {@link #weakCompareAndSetAcquire weakCompareAndSetAcquire},
 156  * {@link #weakCompareAndSetRelease weakCompareAndSetRelease},
 157  * {@link #compareAndExchangeAcquire compareAndExchangeAcquire},
 158  * {@link #compareAndExchange compareAndExchange},
 159  * {@link #compareAndExchangeRelease compareAndExchangeRelease},
 160  * {@link #getAndSet getAndSet},
 161  * {@link #getAndSetAcquire getAndSetAcquire},
 162  * {@link #getAndSetRelease getAndSetRelease}.
 163  * <li>numeric atomic update access modes that, for example, atomically get and
 164  * set with addition the value of a variable under specified memory ordering
 165  * effects.
 166  * The set of corresponding access mode methods belonging to this group
 167  * consists of the methods
 168  * {@link #getAndAdd getAndAdd},
 169  * {@link #getAndAddAcquire getAndAddAcquire},
 170  * {@link #getAndAddRelease getAndAddRelease},
 171  * <li>bitwise atomic update access modes that, for example, atomically get and
 172  * bitwise OR the value of a variable under specified memory ordering
 173  * effects.
 174  * The set of corresponding access mode methods belonging to this group
 175  * consists of the methods
 176  * {@link #getAndBitwiseOr getAndBitwiseOr},
 177  * {@link #getAndBitwiseOrAcquire getAndBitwiseOrAcquire},
 178  * {@link #getAndBitwiseOrRelease getAndBitwiseOrRelease},
 179  * {@link #getAndBitwiseAnd getAndBitwiseAnd},
 180  * {@link #getAndBitwiseAndAcquire getAndBitwiseAndAcquire},
 181  * {@link #getAndBitwiseAndRelease getAndBitwiseAndRelease},
 182  * {@link #getAndBitwiseXor getAndBitwiseXor},
 183  * {@link #getAndBitwiseXorAcquire getAndBitwiseXorAcquire},
 184  * {@link #getAndBitwiseXorRelease getAndBitwiseXorRelease}.
 185  * </ul>
 186  *
 187  * <p>Factory methods that produce or {@link java.lang.invoke.MethodHandles.Lookup
 188  * lookup} VarHandle instances document the set of access modes that are
 189  * supported, which may also include documenting restrictions based on the
 190  * variable type and whether a variable is read-only.  If an access mode is not
 191  * supported then the corresponding access mode method will on invocation throw
 192  * an {@code UnsupportedOperationException}.  Factory methods should document
 193  * any additional undeclared exceptions that may be thrown by access mode
 194  * methods.
 195  * The {@link #get get} access mode is supported for all
 196  * VarHandle instances and the corresponding method never throws
 197  * {@code UnsupportedOperationException}.
 198  * If a VarHandle references a read-only variable (for example a {@code final}
 199  * field) then write, atomic update, numeric atomic update, and bitwise atomic
 200  * update access modes are not supported and corresponding methods throw
 201  * {@code UnsupportedOperationException}.
 202  * Read/write access modes (if supported), with the exception of
 203  * {@code get} and {@code set}, provide atomic access for
 204  * reference types and all primitive types.
 205  * Unless stated otherwise in the documentation of a factory method, the access
 206  * modes {@code get} and {@code set} (if supported) provide atomic access for
 207  * reference types and all primitives types, with the exception of {@code long}
 208  * and {@code double} on 32-bit platforms.
 209  *
 210  * <p>Access modes will override any memory ordering effects specified at
 211  * the declaration site of a variable.  For example, a VarHandle accessing
 212  * a field using the {@code get} access mode will access the field as
 213  * specified <em>by its access mode</em> even if that field is declared
 214  * {@code volatile}.  When mixed access is performed extreme care should be
 215  * taken since the Java Memory Model may permit surprising results.
 216  *
 217  * <p>In addition to supporting access to variables under various access modes,
 218  * a set of static methods, referred to as memory fence methods, is also
 219  * provided for fine-grained control of memory ordering.
 220  *
 221  * The Java Language Specification permits other threads to observe operations
 222  * as if they were executed in orders different than are apparent in program
 223  * source code, subject to constraints arising, for example, from the use of
 224  * locks, {@code volatile} fields or VarHandles.  The static methods,
 225  * {@link #fullFence fullFence}, {@link #acquireFence acquireFence},
 226  * {@link #releaseFence releaseFence}, {@link #loadLoadFence loadLoadFence} and
 227  * {@link #storeStoreFence storeStoreFence}, can also be used to impose
 228  * constraints.  Their specifications, as is the case for certain access modes,
 229  * are phrased in terms of the lack of "reorderings" -- observable ordering
 230  * effects that might otherwise occur if the fence was not present.  More
 231  * precise phrasing of the specification of access mode methods and memory fence
 232  * methods may accompany future updates of the Java Language Specification.
 233  *
 234  * <h2>Compiling invocation of access mode methods</h2>
 235  * A Java method call expression naming an access mode method can invoke a
 236  * VarHandle from Java source code.  From the viewpoint of source code, these
 237  * methods can take any arguments and their polymorphic result (if expressed)
 238  * can be cast to any return type.  Formally this is accomplished by giving the
 239  * access mode methods variable arity {@code Object} arguments and
 240  * {@code Object} return types (if the return type is polymorphic), but they
 241  * have an additional quality called <em>signature polymorphism</em> which
 242  * connects this freedom of invocation directly to the JVM execution stack.
 243  * <p>
 244  * As is usual with virtual methods, source-level calls to access mode methods
 245  * compile to an {@code invokevirtual} instruction.  More unusually, the
 246  * compiler must record the actual argument types, and may not perform method
 247  * invocation conversions on the arguments.  Instead, it must generate
 248  * instructions to push them on the stack according to their own unconverted
 249  * types.  The VarHandle object itself will be pushed on the stack before the
 250  * arguments.  The compiler then generates an {@code invokevirtual} instruction
 251  * that invokes the access mode method with a symbolic type descriptor which
 252  * describes the argument and return types.
 253  * <p>
 254  * To issue a complete symbolic type descriptor, the compiler must also
 255  * determine the return type (if polymorphic).  This is based on a cast on the
 256  * method invocation expression, if there is one, or else {@code Object} if the
 257  * invocation is an expression, or else {@code void} if the invocation is a
 258  * statement.  The cast may be to a primitive type (but not {@code void}).
 259  * <p>
 260  * As a corner case, an uncasted {@code null} argument is given a symbolic type
 261  * descriptor of {@code java.lang.Void}.  The ambiguity with the type
 262  * {@code Void} is harmless, since there are no references of type {@code Void}
 263  * except the null reference.
 264  *
 265  *
 266  * <h2><a id="invoke">Performing invocation of access mode methods</a></h2>
 267  * The first time an {@code invokevirtual} instruction is executed it is linked
 268  * by symbolically resolving the names in the instruction and verifying that
 269  * the method call is statically legal.  This also holds for calls to access mode
 270  * methods.  In this case, the symbolic type descriptor emitted by the compiler
 271  * is checked for correct syntax, and names it contains are resolved.  Thus, an
 272  * {@code invokevirtual} instruction which invokes an access mode method will
 273  * always link, as long as the symbolic type descriptor is syntactically
 274  * well-formed and the types exist.
 275  * <p>
 276  * When the {@code invokevirtual} is executed after linking, the receiving
 277  * VarHandle's access mode type is first checked by the JVM to ensure that it
 278  * matches the symbolic type descriptor.  If the type
 279  * match fails, it means that the access mode method which the caller is
 280  * invoking is not present on the individual VarHandle being invoked.
 281  *
 282  * <p id="invoke-behavior">
 283  * Invocation of an access mode method behaves, by default, as if an invocation of
 284  * {@link MethodHandle#invoke}, where the receiving method handle accepts the
 285  * VarHandle instance as the leading argument.  More specifically, the
 286  * following, where {@code {access-mode}} corresponds to the access mode method
 287  * name:
 288  * <pre> {@code
 289  * VarHandle vh = ..
 290  * R r = (R) vh.{access-mode}(p1, p2, ..., pN);
 291  * }</pre>
 292  * behaves as if:
 293  * <pre> {@code
 294  * VarHandle vh = ..
 295  * VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}");
 296  * MethodHandle mh = MethodHandles.varHandleExactInvoker(
 297  *                       am,
 298  *                       vh.accessModeType(am));
 299  *
 300  * R r = (R) mh.invoke(vh, p1, p2, ..., pN)
 301  * }</pre>
 302  * (modulo access mode methods do not declare throwing of {@code Throwable}).
 303  * This is equivalent to:
 304  * <pre> {@code
 305  * MethodHandle mh = MethodHandles.lookup().findVirtual(
 306  *                       VarHandle.class,
 307  *                       "{access-mode}",
 308  *                       MethodType.methodType(R, p1, p2, ..., pN));
 309  *
 310  * R r = (R) mh.invokeExact(vh, p1, p2, ..., pN)
 311  * }</pre>
 312  * where the desired method type is the symbolic type descriptor and a
 313  * {@link MethodHandle#invokeExact} is performed, since before invocation of the
 314  * target, the handle will apply reference casts as necessary and box, unbox, or
 315  * widen primitive values, as if by {@link MethodHandle#asType asType} (see also
 316  * {@link MethodHandles#varHandleInvoker}).
 317  *
 318  * More concisely, such behavior is equivalent to:
 319  * <pre> {@code
 320  * VarHandle vh = ..
 321  * VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}");
 322  * MethodHandle mh = vh.toMethodHandle(am);
 323  *
 324  * R r = (R) mh.invoke(p1, p2, ..., pN)
 325  * }</pre>
 326  * Where, in this case, the method handle is bound to the VarHandle instance.
 327  *
 328  * <p id="invoke-exact-behavior">
 329  * A VarHandle's invocation behavior can be adjusted (see {@link #withInvokeExactBehavior}) such that invocation of
 330  * an access mode method behaves as if invocation of {@link MethodHandle#invokeExact},
 331  * where the receiving method handle accepts the VarHandle instance as the leading argument.
 332  * More specifically, the following, where {@code {access-mode}} corresponds to the access mode method
 333  * name:
 334  * <pre> {@code
 335  * VarHandle vh = ..
 336  * R r = (R) vh.{access-mode}(p1, p2, ..., pN);
 337  * }</pre>
 338  * behaves as if:
 339  * <pre> {@code
 340  * VarHandle vh = ..
 341  * VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}");
 342  * MethodHandle mh = MethodHandles.varHandleExactInvoker(
 343  *                       am,
 344  *                       vh.accessModeType(am));
 345  *
 346  * R r = (R) mh.invokeExact(vh, p1, p2, ..., pN)
 347  * }</pre>
 348  * (modulo access mode methods do not declare throwing of {@code Throwable}).
 349  *
 350  * More concisely, such behavior is equivalent to:
 351  * <pre> {@code
 352  * VarHandle vh = ..
 353  * VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}");
 354  * MethodHandle mh = vh.toMethodHandle(am);
 355  *
 356  * R r = (R) mh.invokeExact(p1, p2, ..., pN)
 357  * }</pre>
 358  * Where, in this case, the method handle is bound to the VarHandle instance.
 359  *
 360  * <h2>Invocation checking</h2>
 361  * In typical programs, VarHandle access mode type matching will usually
 362  * succeed.  But if a match fails, the JVM will throw a
 363  * {@link WrongMethodTypeException}.
 364  * <p>
 365  * Thus, an access mode type mismatch which might show up as a linkage error
 366  * in a statically typed program can show up as a dynamic
 367  * {@code WrongMethodTypeException} in a program which uses VarHandles.
 368  * <p>
 369  * Because access mode types contain "live" {@code Class} objects, method type
 370  * matching takes into account both type names and class loaders.
 371  * Thus, even if a VarHandle {@code VH} is created in one class loader
 372  * {@code L1} and used in another {@code L2}, VarHandle access mode method
 373  * calls are type-safe, because the caller's symbolic type descriptor, as
 374  * resolved in {@code L2}, is matched against the original callee method's
 375  * symbolic type descriptor, as resolved in {@code L1}.  The resolution in
 376  * {@code L1} happens when {@code VH} is created and its access mode types are
 377  * assigned, while the resolution in {@code L2} happens when the
 378  * {@code invokevirtual} instruction is linked.
 379  * <p>
 380  * Apart from type descriptor checks, a VarHandles's capability to
 381  * access its variables is unrestricted.
 382  * If a VarHandle is formed on a non-public variable by a class that has access
 383  * to that variable, the resulting VarHandle can be used in any place by any
 384  * caller who receives a reference to it.
 385  * <p>
 386  * Unlike with the Core Reflection API, where access is checked every time a
 387  * reflective method is invoked, VarHandle access checking is performed
 388  * <a href="MethodHandles.Lookup.html#access">when the VarHandle is
 389  * created</a>.
 390  * Thus, VarHandles to non-public variables, or to variables in non-public
 391  * classes, should generally be kept secret.  They should not be passed to
 392  * untrusted code unless their use from the untrusted code would be harmless.
 393  *
 394  *
 395  * <h2>VarHandle creation</h2>
 396  * Java code can create a VarHandle that directly accesses any field that is
 397  * accessible to that code.  This is done via a reflective, capability-based
 398  * API called {@link java.lang.invoke.MethodHandles.Lookup
 399  * MethodHandles.Lookup}.
 400  * For example, a VarHandle for a non-static field can be obtained
 401  * from {@link java.lang.invoke.MethodHandles.Lookup#findVarHandle
 402  * Lookup.findVarHandle}.
 403  * There is also a conversion method from Core Reflection API objects,
 404  * {@link java.lang.invoke.MethodHandles.Lookup#unreflectVarHandle
 405  * Lookup.unreflectVarHandle}.
 406  * <p>
 407  * Access to protected field members is restricted to receivers only of the
 408  * accessing class, or one of its subclasses, and the accessing class must in
 409  * turn be a subclass (or package sibling) of the protected member's defining
 410  * class.  If a VarHandle refers to a protected non-static field of a declaring
 411  * class outside the current package, the receiver argument will be narrowed to
 412  * the type of the accessing class.
 413  *
 414  * <h2>Interoperation between VarHandles and the Core Reflection API</h2>
 415  * Using factory methods in the {@link java.lang.invoke.MethodHandles.Lookup
 416  * Lookup} API, any field represented by a Core Reflection API object
 417  * can be converted to a behaviorally equivalent VarHandle.
 418  * For example, a reflective {@link java.lang.reflect.Field Field} can
 419  * be converted to a VarHandle using
 420  * {@link java.lang.invoke.MethodHandles.Lookup#unreflectVarHandle
 421  * Lookup.unreflectVarHandle}.
 422  * The resulting VarHandles generally provide more direct and efficient
 423  * access to the underlying fields.
 424  * <p>
 425  * As a special case, when the Core Reflection API is used to view the
 426  * signature polymorphic access mode methods in this class, they appear as
 427  * ordinary non-polymorphic methods.  Their reflective appearance, as viewed by
 428  * {@link java.lang.Class#getDeclaredMethod Class.getDeclaredMethod},
 429  * is unaffected by their special status in this API.
 430  * For example, {@link java.lang.reflect.Method#getModifiers
 431  * Method.getModifiers}
 432  * will report exactly those modifier bits required for any similarly
 433  * declared method, including in this case {@code native} and {@code varargs}
 434  * bits.
 435  * <p>
 436  * As with any reflected method, these methods (when reflected) may be invoked
 437  * directly via {@link java.lang.reflect.Method#invoke java.lang.reflect.Method.invoke},
 438  * via JNI, or indirectly via
 439  * {@link java.lang.invoke.MethodHandles.Lookup#unreflect Lookup.unreflect}.
 440  * However, such reflective calls do not result in access mode method
 441  * invocations.  Such a call, if passed the required argument (a single one, of
 442  * type {@code Object[]}), will ignore the argument and will throw an
 443  * {@code UnsupportedOperationException}.
 444  * <p>
 445  * Since {@code invokevirtual} instructions can natively invoke VarHandle
 446  * access mode methods under any symbolic type descriptor, this reflective view
 447  * conflicts with the normal presentation of these methods via bytecodes.
 448  * Thus, these native methods, when reflectively viewed by
 449  * {@code Class.getDeclaredMethod}, may be regarded as placeholders only.
 450  * <p>
 451  * In order to obtain an invoker method for a particular access mode type,
 452  * use {@link java.lang.invoke.MethodHandles#varHandleExactInvoker} or
 453  * {@link java.lang.invoke.MethodHandles#varHandleInvoker}.  The
 454  * {@link java.lang.invoke.MethodHandles.Lookup#findVirtual Lookup.findVirtual}
 455  * API is also able to return a method handle to call an access mode method for
 456  * any specified access mode type and is equivalent in behavior to
 457  * {@link java.lang.invoke.MethodHandles#varHandleInvoker}.
 458  *
 459  * <h2>Interoperation between VarHandles and Java generics</h2>
 460  * A VarHandle can be obtained for a variable, such as a field, which is
 461  * declared with Java generic types.  As with the Core Reflection API, the
 462  * VarHandle's variable type will be constructed from the erasure of the
 463  * source-level type.  When a VarHandle access mode method is invoked, the
 464  * types
 465  * of its arguments or the return value cast type may be generic types or type
 466  * instances.  If this occurs, the compiler will replace those types by their
 467  * erasures when it constructs the symbolic type descriptor for the
 468  * {@code invokevirtual} instruction.
 469  *
 470  * @see MethodHandle
 471  * @see MethodHandles
 472  * @see MethodType
 473  * @since 9
 474  */
 475 public abstract sealed class VarHandle implements Constable
 476      permits IndirectVarHandle, LazyInitializingVarHandle,
 477              VarHandleSegmentViewBase,
 478              VarHandleByteArrayAsChars.ByteArrayViewVarHandle,
 479              VarHandleByteArrayAsDoubles.ByteArrayViewVarHandle,
 480              VarHandleByteArrayAsFloats.ByteArrayViewVarHandle,
 481              VarHandleByteArrayAsInts.ByteArrayViewVarHandle,
 482              VarHandleByteArrayAsLongs.ByteArrayViewVarHandle,
 483              VarHandleByteArrayAsShorts.ByteArrayViewVarHandle,
 484              VarHandleBooleans.Array,
 485              VarHandleBooleans.FieldInstanceReadOnly,
 486              VarHandleBooleans.FieldStaticReadOnly,
 487              VarHandleBytes.Array,
 488              VarHandleBytes.FieldInstanceReadOnly,
 489              VarHandleBytes.FieldStaticReadOnly,
 490              VarHandleChars.Array,
 491              VarHandleChars.FieldInstanceReadOnly,
 492              VarHandleChars.FieldStaticReadOnly,
 493              VarHandleDoubles.Array,
 494              VarHandleDoubles.FieldInstanceReadOnly,
 495              VarHandleDoubles.FieldStaticReadOnly,
 496              VarHandleFloats.Array,
 497              VarHandleFloats.FieldInstanceReadOnly,
 498              VarHandleFloats.FieldStaticReadOnly,
 499              VarHandleInts.Array,
 500              VarHandleInts.FieldInstanceReadOnly,
 501              VarHandleInts.FieldStaticReadOnly,
 502              VarHandleLongs.Array,
 503              VarHandleLongs.FieldInstanceReadOnly,
 504              VarHandleLongs.FieldStaticReadOnly,
 505              VarHandleReferences.Array,
 506              VarHandleReferences.FieldInstanceReadOnly,
 507              VarHandleReferences.FieldStaticReadOnly,
 508              VarHandleShorts.Array,
 509              VarHandleShorts.FieldInstanceReadOnly,
 510              VarHandleShorts.FieldStaticReadOnly,
 511              VarHandleValues.Array,
 512              VarHandleValues.FieldInstanceReadOnly,
 513              VarHandleValues.FieldStaticReadOnly {
 514     final VarForm vform;
 515     final boolean exact;
 516 
 517     VarHandle(VarForm vform) {
 518         this(vform, false);
 519     }
 520 
 521     VarHandle(VarForm vform, boolean exact) {
 522         this.vform = vform;
 523         this.exact = exact;
 524     }
 525 
 526     /**
 527      * Returns the target VarHandle.   Subclasses may override this method to implement
 528      * additional logic for example lazily initializing the declaring class of a static field var handle.
 529      */
 530     @ForceInline
 531     VarHandle target() {
 532         return asDirect();
 533     }
 534 
 535     /**
 536      * Returns the direct target VarHandle.   Indirect VarHandle subclasses should implement
 537      * this method.
 538      *
 539      * @see #getMethodHandle(int)
 540      * @see #checkAccessModeThenIsDirect(AccessDescriptor)
 541      */
 542     @ForceInline
 543     VarHandle asDirect() {
 544         return this;
 545     }
 546 
 547     /**
 548      * Returns {@code true} if this VarHandle has <a href="#invoke-exact-behavior"><em>invoke-exact behavior</em></a>.
 549      *
 550      * @see #withInvokeExactBehavior()
 551      * @see #withInvokeBehavior()
 552      * @return {@code true} if this VarHandle has <a href="#invoke-exact-behavior"><em>invoke-exact behavior</em></a>.
 553      * @since 16
 554      */
 555     public boolean hasInvokeExactBehavior() {
 556         return exact;
 557     }
 558 
 559     // Plain accessors
 560 
 561     /**
 562      * Returns the value of a variable, with memory semantics of reading as
 563      * if the variable was declared non-{@code volatile}.  Commonly referred to
 564      * as plain read access.
 565      *
 566      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn)T}.
 567      *
 568      * <p>The symbolic type descriptor at the call site of {@code get}
 569      * must match the access mode type that is the result of calling
 570      * {@code accessModeType(VarHandle.AccessMode.GET)} on this VarHandle.
 571      *
 572      * <p>This access mode is supported by all VarHandle instances and never
 573      * throws {@code UnsupportedOperationException}.
 574      *
 575      * @param args the signature-polymorphic parameter list of the form
 576      * {@code (CT1 ct1, ..., CTn)}
 577      * , statically represented using varargs.
 578      * @return the signature-polymorphic result that is the value of the
 579      * variable
 580      * , statically represented using {@code Object}.
 581      * @throws WrongMethodTypeException if the access mode type does not
 582      * match the caller's symbolic type descriptor.
 583      * @throws ClassCastException if the access mode type matches the caller's
 584      * symbolic type descriptor, but a reference cast fails.
 585      */
 586     public final native
 587     @MethodHandle.PolymorphicSignature
 588     @IntrinsicCandidate
 589     Object get(Object... args);
 590 
 591     /**
 592      * Sets the value of a variable to the {@code newValue}, with memory
 593      * semantics of setting as if the variable was declared non-{@code volatile}
 594      * and non-{@code final}.  Commonly referred to as plain write access.
 595      *
 596      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)void}
 597      *
 598      * <p>The symbolic type descriptor at the call site of {@code set}
 599      * must match the access mode type that is the result of calling
 600      * {@code accessModeType(VarHandle.AccessMode.SET)} on this VarHandle.
 601      *
 602      * @param args the signature-polymorphic parameter list of the form
 603      * {@code (CT1 ct1, ..., CTn ctn, T newValue)}
 604      * , statically represented using varargs.
 605      * @throws UnsupportedOperationException if the access mode is unsupported
 606      * for this VarHandle.
 607      * @throws WrongMethodTypeException if the access mode type does not
 608      * match the caller's symbolic type descriptor.
 609      * @throws ClassCastException if the access mode type matches the caller's
 610      * symbolic type descriptor, but a reference cast fails.
 611      */
 612     public final native
 613     @MethodHandle.PolymorphicSignature
 614     @IntrinsicCandidate
 615     void set(Object... args);
 616 
 617 
 618     // Volatile accessors
 619 
 620     /**
 621      * Returns the value of a variable, with memory semantics of reading as if
 622      * the variable was declared {@code volatile}.
 623      *
 624      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn)T}.
 625      *
 626      * <p>The symbolic type descriptor at the call site of {@code getVolatile}
 627      * must match the access mode type that is the result of calling
 628      * {@code accessModeType(VarHandle.AccessMode.GET_VOLATILE)} on this
 629      * VarHandle.
 630      *
 631      * @param args the signature-polymorphic parameter list of the form
 632      * {@code (CT1 ct1, ..., CTn ctn)}
 633      * , statically represented using varargs.
 634      * @return the signature-polymorphic result that is the value of the
 635      * variable
 636      * , statically represented using {@code Object}.
 637      * @throws UnsupportedOperationException if the access mode is unsupported
 638      * for this VarHandle.
 639      * @throws WrongMethodTypeException if the access mode type does not
 640      * match the caller's symbolic type descriptor.
 641      * @throws ClassCastException if the access mode type matches the caller's
 642      * symbolic type descriptor, but a reference cast fails.
 643      */
 644     public final native
 645     @MethodHandle.PolymorphicSignature
 646     @IntrinsicCandidate
 647     Object getVolatile(Object... args);
 648 
 649     /**
 650      * Sets the value of a variable to the {@code newValue}, with memory
 651      * semantics of setting as if the variable was declared {@code volatile}.
 652      *
 653      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)void}.
 654      *
 655      * <p>The symbolic type descriptor at the call site of {@code setVolatile}
 656      * must match the access mode type that is the result of calling
 657      * {@code accessModeType(VarHandle.AccessMode.SET_VOLATILE)} on this
 658      * VarHandle.
 659      *
 660      * @apiNote
 661      * Ignoring the many semantic differences from C and C++, this method has
 662      * memory ordering effects compatible with {@code memory_order_seq_cst}.
 663      *
 664      * @param args the signature-polymorphic parameter list of the form
 665      * {@code (CT1 ct1, ..., CTn ctn, T newValue)}
 666      * , statically represented using varargs.
 667      * @throws UnsupportedOperationException if the access mode is unsupported
 668      * for this VarHandle.
 669      * @throws WrongMethodTypeException if the access mode type does not
 670      * match the caller's symbolic type descriptor.
 671      * @throws ClassCastException if the access mode type matches the caller's
 672      * symbolic type descriptor, but a reference cast fails.
 673      */
 674     public final native
 675     @MethodHandle.PolymorphicSignature
 676     @IntrinsicCandidate
 677     void setVolatile(Object... args);
 678 
 679 
 680     /**
 681      * Returns the value of a variable, accessed in program order, but with no
 682      * assurance of memory ordering effects with respect to other threads.
 683      *
 684      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn)T}.
 685      *
 686      * <p>The symbolic type descriptor at the call site of {@code getOpaque}
 687      * must match the access mode type that is the result of calling
 688      * {@code accessModeType(VarHandle.AccessMode.GET_OPAQUE)} on this
 689      * VarHandle.
 690      *
 691      * @param args the signature-polymorphic parameter list of the form
 692      * {@code (CT1 ct1, ..., CTn ctn)}
 693      * , statically represented using varargs.
 694      * @return the signature-polymorphic result that is the value of the
 695      * variable
 696      * , statically represented using {@code Object}.
 697      * @throws UnsupportedOperationException if the access mode is unsupported
 698      * for this VarHandle.
 699      * @throws WrongMethodTypeException if the access mode type does not
 700      * match the caller's symbolic type descriptor.
 701      * @throws ClassCastException if the access mode type matches the caller's
 702      * symbolic type descriptor, but a reference cast fails.
 703      */
 704     public final native
 705     @MethodHandle.PolymorphicSignature
 706     @IntrinsicCandidate
 707     Object getOpaque(Object... args);
 708 
 709     /**
 710      * Sets the value of a variable to the {@code newValue}, in program order,
 711      * but with no assurance of memory ordering effects with respect to other
 712      * threads.
 713      *
 714      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)void}.
 715      *
 716      * <p>The symbolic type descriptor at the call site of {@code setOpaque}
 717      * must match the access mode type that is the result of calling
 718      * {@code accessModeType(VarHandle.AccessMode.SET_OPAQUE)} on this
 719      * VarHandle.
 720      *
 721      * @param args the signature-polymorphic parameter list of the form
 722      * {@code (CT1 ct1, ..., CTn ctn, T newValue)}
 723      * , statically represented using varargs.
 724      * @throws UnsupportedOperationException if the access mode is unsupported
 725      * for this VarHandle.
 726      * @throws WrongMethodTypeException if the access mode type does not
 727      * match the caller's symbolic type descriptor.
 728      * @throws ClassCastException if the access mode type matches the caller's
 729      * symbolic type descriptor, but a reference cast fails.
 730      */
 731     public final native
 732     @MethodHandle.PolymorphicSignature
 733     @IntrinsicCandidate
 734     void setOpaque(Object... args);
 735 
 736 
 737     // Lazy accessors
 738 
 739     /**
 740      * Returns the value of a variable, and ensures that subsequent loads and
 741      * stores are not reordered before this access.
 742      *
 743      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn)T}.
 744      *
 745      * <p>The symbolic type descriptor at the call site of {@code getAcquire}
 746      * must match the access mode type that is the result of calling
 747      * {@code accessModeType(VarHandle.AccessMode.GET_ACQUIRE)} on this
 748      * VarHandle.
 749      *
 750      * @apiNote
 751      * Ignoring the many semantic differences from C and C++, this method has
 752      * memory ordering effects compatible with {@code memory_order_acquire}
 753      * ordering.
 754      *
 755      * @param args the signature-polymorphic parameter list of the form
 756      * {@code (CT1 ct1, ..., CTn ctn)}
 757      * , statically represented using varargs.
 758      * @return the signature-polymorphic result that is the value of the
 759      * variable
 760      * , statically represented using {@code Object}.
 761      * @throws UnsupportedOperationException if the access mode is unsupported
 762      * for this VarHandle.
 763      * @throws WrongMethodTypeException if the access mode type does not
 764      * match the caller's symbolic type descriptor.
 765      * @throws ClassCastException if the access mode type matches the caller's
 766      * symbolic type descriptor, but a reference cast fails.
 767      */
 768     public final native
 769     @MethodHandle.PolymorphicSignature
 770     @IntrinsicCandidate
 771     Object getAcquire(Object... args);
 772 
 773     /**
 774      * Sets the value of a variable to the {@code newValue}, and ensures that
 775      * prior loads and stores are not reordered after this access.
 776      *
 777      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)void}.
 778      *
 779      * <p>The symbolic type descriptor at the call site of {@code setRelease}
 780      * must match the access mode type that is the result of calling
 781      * {@code accessModeType(VarHandle.AccessMode.SET_RELEASE)} on this
 782      * VarHandle.
 783      *
 784      * @apiNote
 785      * Ignoring the many semantic differences from C and C++, this method has
 786      * memory ordering effects compatible with {@code memory_order_release}
 787      * ordering.
 788      *
 789      * @param args the signature-polymorphic parameter list of the form
 790      * {@code (CT1 ct1, ..., CTn ctn, T newValue)}
 791      * , statically represented using varargs.
 792      * @throws UnsupportedOperationException if the access mode is unsupported
 793      * for this VarHandle.
 794      * @throws WrongMethodTypeException if the access mode type does not
 795      * match the caller's symbolic type descriptor.
 796      * @throws ClassCastException if the access mode type matches the caller's
 797      * symbolic type descriptor, but a reference cast fails.
 798      */
 799     public final native
 800     @MethodHandle.PolymorphicSignature
 801     @IntrinsicCandidate
 802     void setRelease(Object... args);
 803 
 804 
 805     // Compare and set accessors
 806 
 807     /**
 808      * Atomically sets the value of a variable to the {@code newValue} with the
 809      * memory semantics of {@link #setVolatile} if the variable's current value,
 810      * referred to as the <em>witness value</em>, {@code ==} the
 811      * {@code expectedValue}, as accessed with the memory semantics of
 812      * {@link #getVolatile}.
 813      *
 814      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)boolean}.
 815      *
 816      * <p>The symbolic type descriptor at the call site of {@code
 817      * compareAndSet} must match the access mode type that is the result of
 818      * calling {@code accessModeType(VarHandle.AccessMode.COMPARE_AND_SET)} on
 819      * this VarHandle.
 820      *
 821      * @param args the signature-polymorphic parameter list of the form
 822      * {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
 823      * , statically represented using varargs.
 824      * @return {@code true} if successful, otherwise {@code false} if the
 825      * <em>witness value</em> was not the same as the {@code expectedValue}.
 826      * @throws UnsupportedOperationException if the access mode is unsupported
 827      * for this VarHandle.
 828      * @throws WrongMethodTypeException if the access mode type does not
 829      * match the caller's symbolic type descriptor.
 830      * @throws ClassCastException if the access mode type matches the caller's
 831      * symbolic type descriptor, but a reference cast fails.
 832      * @see #setVolatile(Object...)
 833      * @see #getVolatile(Object...)
 834      */
 835     public final native
 836     @MethodHandle.PolymorphicSignature
 837     @IntrinsicCandidate
 838     boolean compareAndSet(Object... args);
 839 
 840     /**
 841      * Atomically sets the value of a variable to the {@code newValue} with the
 842      * memory semantics of {@link #setVolatile} if the variable's current value,
 843      * referred to as the <em>witness value</em>, {@code ==} the
 844      * {@code expectedValue}, as accessed with the memory semantics of
 845      * {@link #getVolatile}.
 846      *
 847      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)T}.
 848      *
 849      * <p>The symbolic type descriptor at the call site of {@code
 850      * compareAndExchange}
 851      * must match the access mode type that is the result of calling
 852      * {@code accessModeType(VarHandle.AccessMode.COMPARE_AND_EXCHANGE)}
 853      * on this VarHandle.
 854      *
 855      * @param args the signature-polymorphic parameter list of the form
 856      * {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
 857      * , statically represented using varargs.
 858      * @return the signature-polymorphic result that is the <em>witness value</em>, which
 859      * will be the same as the {@code expectedValue} if successful
 860      * , statically represented using {@code Object}.
 861      * @throws UnsupportedOperationException if the access mode is unsupported
 862      * for this VarHandle.
 863      * @throws WrongMethodTypeException if the access mode type is not
 864      * compatible with the caller's symbolic type descriptor.
 865      * @throws ClassCastException if the access mode type is compatible with the
 866      * caller's symbolic type descriptor, but a reference cast fails.
 867      * @see #setVolatile(Object...)
 868      * @see #getVolatile(Object...)
 869      */
 870     public final native
 871     @MethodHandle.PolymorphicSignature
 872     @IntrinsicCandidate
 873     Object compareAndExchange(Object... args);
 874 
 875     /**
 876      * Atomically sets the value of a variable to the {@code newValue} with the
 877      * memory semantics of {@link #set} if the variable's current value,
 878      * referred to as the <em>witness value</em>, {@code ==} the
 879      * {@code expectedValue}, as accessed with the memory semantics of
 880      * {@link #getAcquire}.
 881      *
 882      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)T}.
 883      *
 884      * <p>The symbolic type descriptor at the call site of {@code
 885      * compareAndExchangeAcquire}
 886      * must match the access mode type that is the result of calling
 887      * {@code accessModeType(VarHandle.AccessMode.COMPARE_AND_EXCHANGE_ACQUIRE)} on
 888      * this VarHandle.
 889      *
 890      * @param args the signature-polymorphic parameter list of the form
 891      * {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
 892      * , statically represented using varargs.
 893      * @return the signature-polymorphic result that is the <em>witness value</em>, which
 894      * will be the same as the {@code expectedValue} if successful
 895      * , statically represented using {@code Object}.
 896      * @throws UnsupportedOperationException if the access mode is unsupported
 897      * for this VarHandle.
 898      * @throws WrongMethodTypeException if the access mode type does not
 899      * match the caller's symbolic type descriptor.
 900      * @throws ClassCastException if the access mode type matches the caller's
 901      * symbolic type descriptor, but a reference cast fails.
 902      * @see #set(Object...)
 903      * @see #getAcquire(Object...)
 904      */
 905     public final native
 906     @MethodHandle.PolymorphicSignature
 907     @IntrinsicCandidate
 908     Object compareAndExchangeAcquire(Object... args);
 909 
 910     /**
 911      * Atomically sets the value of a variable to the {@code newValue} with the
 912      * memory semantics of {@link #setRelease} if the variable's current value,
 913      * referred to as the <em>witness value</em>, {@code ==} the
 914      * {@code expectedValue}, as accessed with the memory semantics of
 915      * {@link #get}.
 916      *
 917      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)T}.
 918      *
 919      * <p>The symbolic type descriptor at the call site of {@code
 920      * compareAndExchangeRelease}
 921      * must match the access mode type that is the result of calling
 922      * {@code accessModeType(VarHandle.AccessMode.COMPARE_AND_EXCHANGE_RELEASE)}
 923      * on this VarHandle.
 924      *
 925      * @param args the signature-polymorphic parameter list of the form
 926      * {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
 927      * , statically represented using varargs.
 928      * @return the signature-polymorphic result that is the <em>witness value</em>, which
 929      * will be the same as the {@code expectedValue} if successful
 930      * , statically represented using {@code Object}.
 931      * @throws UnsupportedOperationException if the access mode is unsupported
 932      * for this VarHandle.
 933      * @throws WrongMethodTypeException if the access mode type does not
 934      * match the caller's symbolic type descriptor.
 935      * @throws ClassCastException if the access mode type matches the caller's
 936      * symbolic type descriptor, but a reference cast fails.
 937      * @see #setRelease(Object...)
 938      * @see #get(Object...)
 939      */
 940     public final native
 941     @MethodHandle.PolymorphicSignature
 942     @IntrinsicCandidate
 943     Object compareAndExchangeRelease(Object... args);
 944 
 945     // Weak (spurious failures allowed)
 946 
 947     /**
 948      * Possibly atomically sets the value of a variable to the {@code newValue}
 949      * with the semantics of {@link #set} if the variable's current value,
 950      * referred to as the <em>witness value</em>, {@code ==} the
 951      * {@code expectedValue}, as accessed with the memory semantics of
 952      * {@link #get}.
 953      *
 954      * <p>This operation may fail spuriously (typically, due to memory
 955      * contention) even if the <em>witness value</em> does match the expected value.
 956      *
 957      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)boolean}.
 958      *
 959      * <p>The symbolic type descriptor at the call site of {@code
 960      * weakCompareAndSetPlain} must match the access mode type that is the result of
 961      * calling {@code accessModeType(VarHandle.AccessMode.WEAK_COMPARE_AND_SET_PLAIN)}
 962      * on this VarHandle.
 963      *
 964      * @param args the signature-polymorphic parameter list of the form
 965      * {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
 966      * , statically represented using varargs.
 967      * @return {@code true} if successful, otherwise {@code false} if the
 968      * <em>witness value</em> was not the same as the {@code expectedValue} or if this
 969      * operation spuriously failed.
 970      * @throws UnsupportedOperationException if the access mode is unsupported
 971      * for this VarHandle.
 972      * @throws WrongMethodTypeException if the access mode type does not
 973      * match the caller's symbolic type descriptor.
 974      * @throws ClassCastException if the access mode type matches the caller's
 975      * symbolic type descriptor, but a reference cast fails.
 976      * @see #set(Object...)
 977      * @see #get(Object...)
 978      */
 979     public final native
 980     @MethodHandle.PolymorphicSignature
 981     @IntrinsicCandidate
 982     boolean weakCompareAndSetPlain(Object... args);
 983 
 984     /**
 985      * Possibly atomically sets the value of a variable to the {@code newValue}
 986      * with the memory semantics of {@link #setVolatile} if the variable's
 987      * current value, referred to as the <em>witness value</em>, {@code ==} the
 988      * {@code expectedValue}, as accessed with the memory semantics of
 989      * {@link #getVolatile}.
 990      *
 991      * <p>This operation may fail spuriously (typically, due to memory
 992      * contention) even if the <em>witness value</em> does match the expected value.
 993      *
 994      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)boolean}.
 995      *
 996      * <p>The symbolic type descriptor at the call site of {@code
 997      * weakCompareAndSet} must match the access mode type that is the
 998      * result of calling {@code accessModeType(VarHandle.AccessMode.WEAK_COMPARE_AND_SET)}
 999      * on this VarHandle.
1000      *
1001      * @param args the signature-polymorphic parameter list of the form
1002      * {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
1003      * , statically represented using varargs.
1004      * @return {@code true} if successful, otherwise {@code false} if the
1005      * <em>witness value</em> was not the same as the {@code expectedValue} or if this
1006      * operation spuriously failed.
1007      * @throws UnsupportedOperationException if the access mode is unsupported
1008      * for this VarHandle.
1009      * @throws WrongMethodTypeException if the access mode type does not
1010      * match the caller's symbolic type descriptor.
1011      * @throws ClassCastException if the access mode type matches the caller's
1012      * symbolic type descriptor, but a reference cast fails.
1013      * @see #setVolatile(Object...)
1014      * @see #getVolatile(Object...)
1015      */
1016     public final native
1017     @MethodHandle.PolymorphicSignature
1018     @IntrinsicCandidate
1019     boolean weakCompareAndSet(Object... args);
1020 
1021     /**
1022      * Possibly atomically sets the value of a variable to the {@code newValue}
1023      * with the semantics of {@link #set} if the variable's current value,
1024      * referred to as the <em>witness value</em>, {@code ==} the
1025      * {@code expectedValue}, as accessed with the memory semantics of
1026      * {@link #getAcquire}.
1027      *
1028      * <p>This operation may fail spuriously (typically, due to memory
1029      * contention) even if the <em>witness value</em> does match the expected value.
1030      *
1031      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)boolean}.
1032      *
1033      * <p>The symbolic type descriptor at the call site of {@code
1034      * weakCompareAndSetAcquire}
1035      * must match the access mode type that is the result of calling
1036      * {@code accessModeType(VarHandle.AccessMode.WEAK_COMPARE_AND_SET_ACQUIRE)}
1037      * on this VarHandle.
1038      *
1039      * @param args the signature-polymorphic parameter list of the form
1040      * {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
1041      * , statically represented using varargs.
1042      * @return {@code true} if successful, otherwise {@code false} if the
1043      * <em>witness value</em> was not the same as the {@code expectedValue} or if this
1044      * operation spuriously failed.
1045      * @throws UnsupportedOperationException if the access mode is unsupported
1046      * for this VarHandle.
1047      * @throws WrongMethodTypeException if the access mode type does not
1048      * match the caller's symbolic type descriptor.
1049      * @throws ClassCastException if the access mode type matches the caller's
1050      * symbolic type descriptor, but a reference cast fails.
1051      * @see #set(Object...)
1052      * @see #getAcquire(Object...)
1053      */
1054     public final native
1055     @MethodHandle.PolymorphicSignature
1056     @IntrinsicCandidate
1057     boolean weakCompareAndSetAcquire(Object... args);
1058 
1059     /**
1060      * Possibly atomically sets the value of a variable to the {@code newValue}
1061      * with the semantics of {@link #setRelease} if the variable's current
1062      * value, referred to as the <em>witness value</em>, {@code ==} the
1063      * {@code expectedValue}, as accessed with the memory semantics of
1064      * {@link #get}.
1065      *
1066      * <p>This operation may fail spuriously (typically, due to memory
1067      * contention) even if the <em>witness value</em> does match the expected value.
1068      *
1069      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)boolean}.
1070      *
1071      * <p>The symbolic type descriptor at the call site of {@code
1072      * weakCompareAndSetRelease}
1073      * must match the access mode type that is the result of calling
1074      * {@code accessModeType(VarHandle.AccessMode.WEAK_COMPARE_AND_SET_RELEASE)}
1075      * on this VarHandle.
1076      *
1077      * @param args the signature-polymorphic parameter list of the form
1078      * {@code (CT1 ct1, ..., CTn ctn, T expectedValue, T newValue)}
1079      * , statically represented using varargs.
1080      * @return {@code true} if successful, otherwise {@code false} if the
1081      * <em>witness value</em> was not the same as the {@code expectedValue} or if this
1082      * operation spuriously failed.
1083      * @throws UnsupportedOperationException if the access mode is unsupported
1084      * for this VarHandle.
1085      * @throws WrongMethodTypeException if the access mode type does not
1086      * match the caller's symbolic type descriptor.
1087      * @throws ClassCastException if the access mode type matches the caller's
1088      * symbolic type descriptor, but a reference cast fails.
1089      * @see #setRelease(Object...)
1090      * @see #get(Object...)
1091      */
1092     public final native
1093     @MethodHandle.PolymorphicSignature
1094     @IntrinsicCandidate
1095     boolean weakCompareAndSetRelease(Object... args);
1096 
1097     /**
1098      * Atomically sets the value of a variable to the {@code newValue} with the
1099      * memory semantics of {@link #setVolatile} and returns the variable's
1100      * previous value, as accessed with the memory semantics of
1101      * {@link #getVolatile}.
1102      *
1103      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)T}.
1104      *
1105      * <p>The symbolic type descriptor at the call site of {@code getAndSet}
1106      * must match the access mode type that is the result of calling
1107      * {@code accessModeType(VarHandle.AccessMode.GET_AND_SET)} on this
1108      * VarHandle.
1109      *
1110      * @param args the signature-polymorphic parameter list of the form
1111      * {@code (CT1 ct1, ..., CTn ctn, T newValue)}
1112      * , statically represented using varargs.
1113      * @return the signature-polymorphic result that is the previous value of
1114      * the variable
1115      * , statically represented using {@code Object}.
1116      * @throws UnsupportedOperationException if the access mode is unsupported
1117      * for this VarHandle.
1118      * @throws WrongMethodTypeException if the access mode type does not
1119      * match the caller's symbolic type descriptor.
1120      * @throws ClassCastException if the access mode type matches the caller's
1121      * symbolic type descriptor, but a reference cast fails.
1122      * @see #setVolatile(Object...)
1123      * @see #getVolatile(Object...)
1124      */
1125     public final native
1126     @MethodHandle.PolymorphicSignature
1127     @IntrinsicCandidate
1128     Object getAndSet(Object... args);
1129 
1130     /**
1131      * Atomically sets the value of a variable to the {@code newValue} with the
1132      * memory semantics of {@link #set} and returns the variable's
1133      * previous value, as accessed with the memory semantics of
1134      * {@link #getAcquire}.
1135      *
1136      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)T}.
1137      *
1138      * <p>The symbolic type descriptor at the call site of {@code getAndSetAcquire}
1139      * must match the access mode type that is the result of calling
1140      * {@code accessModeType(VarHandle.AccessMode.GET_AND_SET_ACQUIRE)} on this
1141      * VarHandle.
1142      *
1143      * @param args the signature-polymorphic parameter list of the form
1144      * {@code (CT1 ct1, ..., CTn ctn, T newValue)}
1145      * , statically represented using varargs.
1146      * @return the signature-polymorphic result that is the previous value of
1147      * the variable
1148      * , statically represented using {@code Object}.
1149      * @throws UnsupportedOperationException if the access mode is unsupported
1150      * for this VarHandle.
1151      * @throws WrongMethodTypeException if the access mode type does not
1152      * match the caller's symbolic type descriptor.
1153      * @throws ClassCastException if the access mode type matches the caller's
1154      * symbolic type descriptor, but a reference cast fails.
1155      * @see #setVolatile(Object...)
1156      * @see #getVolatile(Object...)
1157      */
1158     public final native
1159     @MethodHandle.PolymorphicSignature
1160     @IntrinsicCandidate
1161     Object getAndSetAcquire(Object... args);
1162 
1163     /**
1164      * Atomically sets the value of a variable to the {@code newValue} with the
1165      * memory semantics of {@link #setRelease} and returns the variable's
1166      * previous value, as accessed with the memory semantics of
1167      * {@link #get}.
1168      *
1169      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T newValue)T}.
1170      *
1171      * <p>The symbolic type descriptor at the call site of {@code getAndSetRelease}
1172      * must match the access mode type that is the result of calling
1173      * {@code accessModeType(VarHandle.AccessMode.GET_AND_SET_RELEASE)} on this
1174      * VarHandle.
1175      *
1176      * @param args the signature-polymorphic parameter list of the form
1177      * {@code (CT1 ct1, ..., CTn ctn, T newValue)}
1178      * , statically represented using varargs.
1179      * @return the signature-polymorphic result that is the previous value of
1180      * the variable
1181      * , statically represented using {@code Object}.
1182      * @throws UnsupportedOperationException if the access mode is unsupported
1183      * for this VarHandle.
1184      * @throws WrongMethodTypeException if the access mode type does not
1185      * match the caller's symbolic type descriptor.
1186      * @throws ClassCastException if the access mode type matches the caller's
1187      * symbolic type descriptor, but a reference cast fails.
1188      * @see #setVolatile(Object...)
1189      * @see #getVolatile(Object...)
1190      */
1191     public final native
1192     @MethodHandle.PolymorphicSignature
1193     @IntrinsicCandidate
1194     Object getAndSetRelease(Object... args);
1195 
1196     // Primitive adders
1197     // Throw UnsupportedOperationException for refs
1198 
1199     /**
1200      * Atomically adds the {@code value} to the current value of a variable with
1201      * the memory semantics of {@link #setVolatile}, and returns the variable's
1202      * previous value, as accessed with the memory semantics of
1203      * {@link #getVolatile}.
1204      *
1205      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T value)T}.
1206      *
1207      * <p>The symbolic type descriptor at the call site of {@code getAndAdd}
1208      * must match the access mode type that is the result of calling
1209      * {@code accessModeType(VarHandle.AccessMode.GET_AND_ADD)} on this
1210      * VarHandle.
1211      *
1212      * @param args the signature-polymorphic parameter list of the form
1213      * {@code (CT1 ct1, ..., CTn ctn, T value)}
1214      * , statically represented using varargs.
1215      * @return the signature-polymorphic result that is the previous value of
1216      * the variable
1217      * , statically represented using {@code Object}.
1218      * @throws UnsupportedOperationException if the access mode is unsupported
1219      * for this VarHandle.
1220      * @throws WrongMethodTypeException if the access mode type does not
1221      * match the caller's symbolic type descriptor.
1222      * @throws ClassCastException if the access mode type matches the caller's
1223      * symbolic type descriptor, but a reference cast fails.
1224      * @see #setVolatile(Object...)
1225      * @see #getVolatile(Object...)
1226      */
1227     public final native
1228     @MethodHandle.PolymorphicSignature
1229     @IntrinsicCandidate
1230     Object getAndAdd(Object... args);
1231 
1232     /**
1233      * Atomically adds the {@code value} to the current value of a variable with
1234      * the memory semantics of {@link #set}, and returns the variable's
1235      * previous value, as accessed with the memory semantics of
1236      * {@link #getAcquire}.
1237      *
1238      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T value)T}.
1239      *
1240      * <p>The symbolic type descriptor at the call site of {@code getAndAddAcquire}
1241      * must match the access mode type that is the result of calling
1242      * {@code accessModeType(VarHandle.AccessMode.GET_AND_ADD_ACQUIRE)} on this
1243      * VarHandle.
1244      *
1245      * @param args the signature-polymorphic parameter list of the form
1246      * {@code (CT1 ct1, ..., CTn ctn, T value)}
1247      * , statically represented using varargs.
1248      * @return the signature-polymorphic result that is the previous value of
1249      * the variable
1250      * , statically represented using {@code Object}.
1251      * @throws UnsupportedOperationException if the access mode is unsupported
1252      * for this VarHandle.
1253      * @throws WrongMethodTypeException if the access mode type does not
1254      * match the caller's symbolic type descriptor.
1255      * @throws ClassCastException if the access mode type matches the caller's
1256      * symbolic type descriptor, but a reference cast fails.
1257      * @see #setVolatile(Object...)
1258      * @see #getVolatile(Object...)
1259      */
1260     public final native
1261     @MethodHandle.PolymorphicSignature
1262     @IntrinsicCandidate
1263     Object getAndAddAcquire(Object... args);
1264 
1265     /**
1266      * Atomically adds the {@code value} to the current value of a variable with
1267      * the memory semantics of {@link #setRelease}, and returns the variable's
1268      * previous value, as accessed with the memory semantics of
1269      * {@link #get}.
1270      *
1271      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T value)T}.
1272      *
1273      * <p>The symbolic type descriptor at the call site of {@code getAndAddRelease}
1274      * must match the access mode type that is the result of calling
1275      * {@code accessModeType(VarHandle.AccessMode.GET_AND_ADD_RELEASE)} on this
1276      * VarHandle.
1277      *
1278      * @param args the signature-polymorphic parameter list of the form
1279      * {@code (CT1 ct1, ..., CTn ctn, T value)}
1280      * , statically represented using varargs.
1281      * @return the signature-polymorphic result that is the previous value of
1282      * the variable
1283      * , statically represented using {@code Object}.
1284      * @throws UnsupportedOperationException if the access mode is unsupported
1285      * for this VarHandle.
1286      * @throws WrongMethodTypeException if the access mode type does not
1287      * match the caller's symbolic type descriptor.
1288      * @throws ClassCastException if the access mode type matches the caller's
1289      * symbolic type descriptor, but a reference cast fails.
1290      * @see #setVolatile(Object...)
1291      * @see #getVolatile(Object...)
1292      */
1293     public final native
1294     @MethodHandle.PolymorphicSignature
1295     @IntrinsicCandidate
1296     Object getAndAddRelease(Object... args);
1297 
1298 
1299     // Bitwise operations
1300     // Throw UnsupportedOperationException for refs
1301 
1302     /**
1303      * Atomically sets the value of a variable to the result of
1304      * bitwise OR between the variable's current value and the {@code mask}
1305      * with the memory semantics of {@link #setVolatile} and returns the
1306      * variable's previous value, as accessed with the memory semantics of
1307      * {@link #getVolatile}.
1308      *
1309      * <p>If the variable type is the non-integral {@code boolean} type then a
1310      * logical OR is performed instead of a bitwise OR.
1311      *
1312      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T mask)T}.
1313      *
1314      * <p>The symbolic type descriptor at the call site of {@code getAndBitwiseOr}
1315      * must match the access mode type that is the result of calling
1316      * {@code accessModeType(VarHandle.AccessMode.GET_AND_BITWISE_OR)} on this
1317      * VarHandle.
1318      *
1319      * @param args the signature-polymorphic parameter list of the form
1320      * {@code (CT1 ct1, ..., CTn ctn, T mask)}
1321      * , statically represented using varargs.
1322      * @return the signature-polymorphic result that is the previous value of
1323      * the variable
1324      * , statically represented using {@code Object}.
1325      * @throws UnsupportedOperationException if the access mode is unsupported
1326      * for this VarHandle.
1327      * @throws WrongMethodTypeException if the access mode type does not
1328      * match the caller's symbolic type descriptor.
1329      * @throws ClassCastException if the access mode type matches the caller's
1330      * symbolic type descriptor, but a reference cast fails.
1331      * @see #setVolatile(Object...)
1332      * @see #getVolatile(Object...)
1333      */
1334     public final native
1335     @MethodHandle.PolymorphicSignature
1336     @IntrinsicCandidate
1337     Object getAndBitwiseOr(Object... args);
1338 
1339     /**
1340      * Atomically sets the value of a variable to the result of
1341      * bitwise OR between the variable's current value and the {@code mask}
1342      * with the memory semantics of {@link #set} and returns the
1343      * variable's previous value, as accessed with the memory semantics of
1344      * {@link #getAcquire}.
1345      *
1346      * <p>If the variable type is the non-integral {@code boolean} type then a
1347      * logical OR is performed instead of a bitwise OR.
1348      *
1349      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T mask)T}.
1350      *
1351      * <p>The symbolic type descriptor at the call site of {@code getAndBitwiseOrAcquire}
1352      * must match the access mode type that is the result of calling
1353      * {@code accessModeType(VarHandle.AccessMode.GET_AND_BITWISE_OR_ACQUIRE)} on this
1354      * VarHandle.
1355      *
1356      * @param args the signature-polymorphic parameter list of the form
1357      * {@code (CT1 ct1, ..., CTn ctn, T mask)}
1358      * , statically represented using varargs.
1359      * @return the signature-polymorphic result that is the previous value of
1360      * the variable
1361      * , statically represented using {@code Object}.
1362      * @throws UnsupportedOperationException if the access mode is unsupported
1363      * for this VarHandle.
1364      * @throws WrongMethodTypeException if the access mode type does not
1365      * match the caller's symbolic type descriptor.
1366      * @throws ClassCastException if the access mode type matches the caller's
1367      * symbolic type descriptor, but a reference cast fails.
1368      * @see #set(Object...)
1369      * @see #getAcquire(Object...)
1370      */
1371     public final native
1372     @MethodHandle.PolymorphicSignature
1373     @IntrinsicCandidate
1374     Object getAndBitwiseOrAcquire(Object... args);
1375 
1376     /**
1377      * Atomically sets the value of a variable to the result of
1378      * bitwise OR between the variable's current value and the {@code mask}
1379      * with the memory semantics of {@link #setRelease} and returns the
1380      * variable's previous value, as accessed with the memory semantics of
1381      * {@link #get}.
1382      *
1383      * <p>If the variable type is the non-integral {@code boolean} type then a
1384      * logical OR is performed instead of a bitwise OR.
1385      *
1386      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T mask)T}.
1387      *
1388      * <p>The symbolic type descriptor at the call site of {@code getAndBitwiseOrRelease}
1389      * must match the access mode type that is the result of calling
1390      * {@code accessModeType(VarHandle.AccessMode.GET_AND_BITWISE_OR_RELEASE)} on this
1391      * VarHandle.
1392      *
1393      * @param args the signature-polymorphic parameter list of the form
1394      * {@code (CT1 ct1, ..., CTn ctn, T mask)}
1395      * , statically represented using varargs.
1396      * @return the signature-polymorphic result that is the previous value of
1397      * the variable
1398      * , statically represented using {@code Object}.
1399      * @throws UnsupportedOperationException if the access mode is unsupported
1400      * for this VarHandle.
1401      * @throws WrongMethodTypeException if the access mode type does not
1402      * match the caller's symbolic type descriptor.
1403      * @throws ClassCastException if the access mode type matches the caller's
1404      * symbolic type descriptor, but a reference cast fails.
1405      * @see #setRelease(Object...)
1406      * @see #get(Object...)
1407      */
1408     public final native
1409     @MethodHandle.PolymorphicSignature
1410     @IntrinsicCandidate
1411     Object getAndBitwiseOrRelease(Object... args);
1412 
1413     /**
1414      * Atomically sets the value of a variable to the result of
1415      * bitwise AND between the variable's current value and the {@code mask}
1416      * with the memory semantics of {@link #setVolatile} and returns the
1417      * variable's previous value, as accessed with the memory semantics of
1418      * {@link #getVolatile}.
1419      *
1420      * <p>If the variable type is the non-integral {@code boolean} type then a
1421      * logical AND is performed instead of a bitwise AND.
1422      *
1423      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T mask)T}.
1424      *
1425      * <p>The symbolic type descriptor at the call site of {@code getAndBitwiseAnd}
1426      * must match the access mode type that is the result of calling
1427      * {@code accessModeType(VarHandle.AccessMode.GET_AND_BITWISE_AND)} on this
1428      * VarHandle.
1429      *
1430      * @param args the signature-polymorphic parameter list of the form
1431      * {@code (CT1 ct1, ..., CTn ctn, T mask)}
1432      * , statically represented using varargs.
1433      * @return the signature-polymorphic result that is the previous value of
1434      * the variable
1435      * , statically represented using {@code Object}.
1436      * @throws UnsupportedOperationException if the access mode is unsupported
1437      * for this VarHandle.
1438      * @throws WrongMethodTypeException if the access mode type does not
1439      * match the caller's symbolic type descriptor.
1440      * @throws ClassCastException if the access mode type matches the caller's
1441      * symbolic type descriptor, but a reference cast fails.
1442      * @see #setVolatile(Object...)
1443      * @see #getVolatile(Object...)
1444      */
1445     public final native
1446     @MethodHandle.PolymorphicSignature
1447     @IntrinsicCandidate
1448     Object getAndBitwiseAnd(Object... args);
1449 
1450     /**
1451      * Atomically sets the value of a variable to the result of
1452      * bitwise AND between the variable's current value and the {@code mask}
1453      * with the memory semantics of {@link #set} and returns the
1454      * variable's previous value, as accessed with the memory semantics of
1455      * {@link #getAcquire}.
1456      *
1457      * <p>If the variable type is the non-integral {@code boolean} type then a
1458      * logical AND is performed instead of a bitwise AND.
1459      *
1460      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T mask)T}.
1461      *
1462      * <p>The symbolic type descriptor at the call site of {@code getAndBitwiseAndAcquire}
1463      * must match the access mode type that is the result of calling
1464      * {@code accessModeType(VarHandle.AccessMode.GET_AND_BITWISE_AND_ACQUIRE)} on this
1465      * VarHandle.
1466      *
1467      * @param args the signature-polymorphic parameter list of the form
1468      * {@code (CT1 ct1, ..., CTn ctn, T mask)}
1469      * , statically represented using varargs.
1470      * @return the signature-polymorphic result that is the previous value of
1471      * the variable
1472      * , statically represented using {@code Object}.
1473      * @throws UnsupportedOperationException if the access mode is unsupported
1474      * for this VarHandle.
1475      * @throws WrongMethodTypeException if the access mode type does not
1476      * match the caller's symbolic type descriptor.
1477      * @throws ClassCastException if the access mode type matches the caller's
1478      * symbolic type descriptor, but a reference cast fails.
1479      * @see #set(Object...)
1480      * @see #getAcquire(Object...)
1481      */
1482     public final native
1483     @MethodHandle.PolymorphicSignature
1484     @IntrinsicCandidate
1485     Object getAndBitwiseAndAcquire(Object... args);
1486 
1487     /**
1488      * Atomically sets the value of a variable to the result of
1489      * bitwise AND between the variable's current value and the {@code mask}
1490      * with the memory semantics of {@link #setRelease} and returns the
1491      * variable's previous value, as accessed with the memory semantics of
1492      * {@link #get}.
1493      *
1494      * <p>If the variable type is the non-integral {@code boolean} type then a
1495      * logical AND is performed instead of a bitwise AND.
1496      *
1497      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T mask)T}.
1498      *
1499      * <p>The symbolic type descriptor at the call site of {@code getAndBitwiseAndRelease}
1500      * must match the access mode type that is the result of calling
1501      * {@code accessModeType(VarHandle.AccessMode.GET_AND_BITWISE_AND_RELEASE)} on this
1502      * VarHandle.
1503      *
1504      * @param args the signature-polymorphic parameter list of the form
1505      * {@code (CT1 ct1, ..., CTn ctn, T mask)}
1506      * , statically represented using varargs.
1507      * @return the signature-polymorphic result that is the previous value of
1508      * the variable
1509      * , statically represented using {@code Object}.
1510      * @throws UnsupportedOperationException if the access mode is unsupported
1511      * for this VarHandle.
1512      * @throws WrongMethodTypeException if the access mode type does not
1513      * match the caller's symbolic type descriptor.
1514      * @throws ClassCastException if the access mode type matches the caller's
1515      * symbolic type descriptor, but a reference cast fails.
1516      * @see #setRelease(Object...)
1517      * @see #get(Object...)
1518      */
1519     public final native
1520     @MethodHandle.PolymorphicSignature
1521     @IntrinsicCandidate
1522     Object getAndBitwiseAndRelease(Object... args);
1523 
1524     /**
1525      * Atomically sets the value of a variable to the result of
1526      * bitwise XOR between the variable's current value and the {@code mask}
1527      * with the memory semantics of {@link #setVolatile} and returns the
1528      * variable's previous value, as accessed with the memory semantics of
1529      * {@link #getVolatile}.
1530      *
1531      * <p>If the variable type is the non-integral {@code boolean} type then a
1532      * logical XOR is performed instead of a bitwise XOR.
1533      *
1534      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T mask)T}.
1535      *
1536      * <p>The symbolic type descriptor at the call site of {@code getAndBitwiseXor}
1537      * must match the access mode type that is the result of calling
1538      * {@code accessModeType(VarHandle.AccessMode.GET_AND_BITWISE_XOR)} on this
1539      * VarHandle.
1540      *
1541      * @param args the signature-polymorphic parameter list of the form
1542      * {@code (CT1 ct1, ..., CTn ctn, T mask)}
1543      * , statically represented using varargs.
1544      * @return the signature-polymorphic result that is the previous value of
1545      * the variable
1546      * , statically represented using {@code Object}.
1547      * @throws UnsupportedOperationException if the access mode is unsupported
1548      * for this VarHandle.
1549      * @throws WrongMethodTypeException if the access mode type does not
1550      * match the caller's symbolic type descriptor.
1551      * @throws ClassCastException if the access mode type matches the caller's
1552      * symbolic type descriptor, but a reference cast fails.
1553      * @see #setVolatile(Object...)
1554      * @see #getVolatile(Object...)
1555      */
1556     public final native
1557     @MethodHandle.PolymorphicSignature
1558     @IntrinsicCandidate
1559     Object getAndBitwiseXor(Object... args);
1560 
1561     /**
1562      * Atomically sets the value of a variable to the result of
1563      * bitwise XOR between the variable's current value and the {@code mask}
1564      * with the memory semantics of {@link #set} and returns the
1565      * variable's previous value, as accessed with the memory semantics of
1566      * {@link #getAcquire}.
1567      *
1568      * <p>If the variable type is the non-integral {@code boolean} type then a
1569      * logical XOR is performed instead of a bitwise XOR.
1570      *
1571      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T mask)T}.
1572      *
1573      * <p>The symbolic type descriptor at the call site of {@code getAndBitwiseXorAcquire}
1574      * must match the access mode type that is the result of calling
1575      * {@code accessModeType(VarHandle.AccessMode.GET_AND_BITWISE_XOR_ACQUIRE)} on this
1576      * VarHandle.
1577      *
1578      * @param args the signature-polymorphic parameter list of the form
1579      * {@code (CT1 ct1, ..., CTn ctn, T mask)}
1580      * , statically represented using varargs.
1581      * @return the signature-polymorphic result that is the previous value of
1582      * the variable
1583      * , statically represented using {@code Object}.
1584      * @throws UnsupportedOperationException if the access mode is unsupported
1585      * for this VarHandle.
1586      * @throws WrongMethodTypeException if the access mode type does not
1587      * match the caller's symbolic type descriptor.
1588      * @throws ClassCastException if the access mode type matches the caller's
1589      * symbolic type descriptor, but a reference cast fails.
1590      * @see #set(Object...)
1591      * @see #getAcquire(Object...)
1592      */
1593     public final native
1594     @MethodHandle.PolymorphicSignature
1595     @IntrinsicCandidate
1596     Object getAndBitwiseXorAcquire(Object... args);
1597 
1598     /**
1599      * Atomically sets the value of a variable to the result of
1600      * bitwise XOR between the variable's current value and the {@code mask}
1601      * with the memory semantics of {@link #setRelease} and returns the
1602      * variable's previous value, as accessed with the memory semantics of
1603      * {@link #get}.
1604      *
1605      * <p>If the variable type is the non-integral {@code boolean} type then a
1606      * logical XOR is performed instead of a bitwise XOR.
1607      *
1608      * <p>The method signature is of the form {@code (CT1 ct1, ..., CTn ctn, T mask)T}.
1609      *
1610      * <p>The symbolic type descriptor at the call site of {@code getAndBitwiseXorRelease}
1611      * must match the access mode type that is the result of calling
1612      * {@code accessModeType(VarHandle.AccessMode.GET_AND_BITWISE_XOR_RELEASE)} on this
1613      * VarHandle.
1614      *
1615      * @param args the signature-polymorphic parameter list of the form
1616      * {@code (CT1 ct1, ..., CTn ctn, T mask)}
1617      * , statically represented using varargs.
1618      * @return the signature-polymorphic result that is the previous value of
1619      * the variable
1620      * , statically represented using {@code Object}.
1621      * @throws UnsupportedOperationException if the access mode is unsupported
1622      * for this VarHandle.
1623      * @throws WrongMethodTypeException if the access mode type does not
1624      * match the caller's symbolic type descriptor.
1625      * @throws ClassCastException if the access mode type matches the caller's
1626      * symbolic type descriptor, but a reference cast fails.
1627      * @see #setRelease(Object...)
1628      * @see #get(Object...)
1629      */
1630     public final native
1631     @MethodHandle.PolymorphicSignature
1632     @IntrinsicCandidate
1633     Object getAndBitwiseXorRelease(Object... args);
1634 
1635     /**
1636      * Returns a VarHandle, with access to the same variable(s) as this VarHandle, but whose
1637      * invocation behavior of access mode methods is adjusted to
1638      * <a href="#invoke-exact-behavior"><em>invoke-exact behavior</em></a>.
1639      * <p>
1640      * If this VarHandle already has invoke-exact behavior this VarHandle is returned.
1641      * <p>
1642      * Invoking {@link #hasInvokeExactBehavior()} on the returned var handle
1643      * is guaranteed to return {@code true}.
1644      *
1645      * @apiNote
1646      * Invoke-exact behavior guarantees that upon invocation of an access mode method
1647      * the types and arity of the arguments must match the {@link #accessModeType(AccessMode) access mode type},
1648      * otherwise a {@link WrongMethodTypeException} is thrown.
1649      *
1650      * @see #withInvokeBehavior()
1651      * @see #hasInvokeExactBehavior()
1652      * @return a VarHandle with invoke-exact behavior
1653      * @since 16
1654      */
1655     public abstract VarHandle withInvokeExactBehavior();
1656 
1657     /**
1658      * Returns a VarHandle, with access to the same variable(s) as this VarHandle, but whose
1659      * invocation behavior of access mode methods is adjusted to
1660      * <a href="#invoke-behavior"><em>invoke behavior</em></a>.
1661      * <p>
1662      * If this VarHandle already has invoke behavior this VarHandle is returned.
1663      * <p>
1664      * Invoking {@link #hasInvokeExactBehavior()} on the returned var handle
1665      * is guaranteed to return {@code false}.
1666      *
1667      * @see #withInvokeExactBehavior()
1668      * @see #hasInvokeExactBehavior()
1669      * @return a VarHandle with invoke behavior
1670      * @since 16
1671      */
1672     public abstract VarHandle withInvokeBehavior();
1673 
1674     enum AccessType {
1675         GET(Object.class),
1676         SET(void.class),
1677         COMPARE_AND_SET(boolean.class),
1678         COMPARE_AND_EXCHANGE(Object.class),
1679         GET_AND_UPDATE(Object.class);
1680 
1681         static final int COUNT = GET_AND_UPDATE.ordinal() + 1;
1682         static {
1683             assert (COUNT == values().length);
1684         }
1685         final Class<?> returnType;
1686         final boolean isMonomorphicInReturnType;
1687 
1688         AccessType(Class<?> returnType) {
1689             this.returnType = returnType;
1690             isMonomorphicInReturnType = returnType != Object.class;
1691         }
1692 
1693         MethodType accessModeType(Class<?> receiver, Class<?> value,
1694                                   Class<?>... intermediate) {
1695             Class<?>[] ps;
1696             int i;
1697             // the field type (value) is mapped to the return type of MethodType
1698             // the receiver type is mapped to a parameter type of MethodType
1699             // So use the value type if it's a primitive class
1700             if (receiver != null && PrimitiveClass.isPrimitiveClass(receiver)) {
1701                 receiver = PrimitiveClass.asValueType(receiver);
1702             }
1703             switch (this) {
1704                 case GET:
1705                     ps = allocateParameters(0, receiver, intermediate);
1706                     fillParameters(ps, receiver, intermediate);
1707                     return MethodType.methodType(value, ps);
1708                 case SET:
1709                     ps = allocateParameters(1, receiver, intermediate);
1710                     i = fillParameters(ps, receiver, intermediate);
1711                     ps[i] = value;
1712                     return MethodType.methodType(void.class, ps);
1713                 case COMPARE_AND_SET:
1714                     ps = allocateParameters(2, receiver, intermediate);
1715                     i = fillParameters(ps, receiver, intermediate);
1716                     ps[i++] = value;
1717                     ps[i] = value;
1718                     return MethodType.methodType(boolean.class, ps);
1719                 case COMPARE_AND_EXCHANGE:
1720                     ps = allocateParameters(2, receiver, intermediate);
1721                     i = fillParameters(ps, receiver, intermediate);
1722                     ps[i++] = value;
1723                     ps[i] = value;
1724                     return MethodType.methodType(value, ps);
1725                 case GET_AND_UPDATE:
1726                     ps = allocateParameters(1, receiver, intermediate);
1727                     i = fillParameters(ps, receiver, intermediate);
1728                     ps[i] = value;
1729                     return MethodType.methodType(value, ps);
1730                 default:
1731                     throw new InternalError("Unknown AccessType");
1732             }
1733         }
1734 
1735         private static Class<?>[] allocateParameters(int values,
1736                                                      Class<?> receiver, Class<?>... intermediate) {
1737             int size = ((receiver != null) ? 1 : 0) + intermediate.length + values;
1738             return new Class<?>[size];
1739         }
1740 
1741         private static int fillParameters(Class<?>[] ps,
1742                                           Class<?> receiver, Class<?>... intermediate) {
1743             int i = 0;
1744             if (receiver != null)
1745                 ps[i++] = receiver;
1746             for (int j = 0; j < intermediate.length; j++)
1747                 ps[i++] = intermediate[j];
1748             return i;
1749         }
1750     }
1751 
1752     /**
1753      * The set of access modes that specify how a variable, referenced by a
1754      * VarHandle, is accessed.
1755      */
1756     public enum AccessMode {
1757         /**
1758          * The access mode whose access is specified by the corresponding
1759          * method
1760          * {@link VarHandle#get VarHandle.get}
1761          */
1762         GET("get", AccessType.GET),
1763         /**
1764          * The access mode whose access is specified by the corresponding
1765          * method
1766          * {@link VarHandle#set VarHandle.set}
1767          */
1768         SET("set", AccessType.SET),
1769         /**
1770          * The access mode whose access is specified by the corresponding
1771          * method
1772          * {@link VarHandle#getVolatile VarHandle.getVolatile}
1773          */
1774         GET_VOLATILE("getVolatile", AccessType.GET),
1775         /**
1776          * The access mode whose access is specified by the corresponding
1777          * method
1778          * {@link VarHandle#setVolatile VarHandle.setVolatile}
1779          */
1780         SET_VOLATILE("setVolatile", AccessType.SET),
1781         /**
1782          * The access mode whose access is specified by the corresponding
1783          * method
1784          * {@link VarHandle#getAcquire VarHandle.getAcquire}
1785          */
1786         GET_ACQUIRE("getAcquire", AccessType.GET),
1787         /**
1788          * The access mode whose access is specified by the corresponding
1789          * method
1790          * {@link VarHandle#setRelease VarHandle.setRelease}
1791          */
1792         SET_RELEASE("setRelease", AccessType.SET),
1793         /**
1794          * The access mode whose access is specified by the corresponding
1795          * method
1796          * {@link VarHandle#getOpaque VarHandle.getOpaque}
1797          */
1798         GET_OPAQUE("getOpaque", AccessType.GET),
1799         /**
1800          * The access mode whose access is specified by the corresponding
1801          * method
1802          * {@link VarHandle#setOpaque VarHandle.setOpaque}
1803          */
1804         SET_OPAQUE("setOpaque", AccessType.SET),
1805         /**
1806          * The access mode whose access is specified by the corresponding
1807          * method
1808          * {@link VarHandle#compareAndSet VarHandle.compareAndSet}
1809          */
1810         COMPARE_AND_SET("compareAndSet", AccessType.COMPARE_AND_SET),
1811         /**
1812          * The access mode whose access is specified by the corresponding
1813          * method
1814          * {@link VarHandle#compareAndExchange VarHandle.compareAndExchange}
1815          */
1816         COMPARE_AND_EXCHANGE("compareAndExchange", AccessType.COMPARE_AND_EXCHANGE),
1817         /**
1818          * The access mode whose access is specified by the corresponding
1819          * method
1820          * {@link VarHandle#compareAndExchangeAcquire VarHandle.compareAndExchangeAcquire}
1821          */
1822         COMPARE_AND_EXCHANGE_ACQUIRE("compareAndExchangeAcquire", AccessType.COMPARE_AND_EXCHANGE),
1823         /**
1824          * The access mode whose access is specified by the corresponding
1825          * method
1826          * {@link VarHandle#compareAndExchangeRelease VarHandle.compareAndExchangeRelease}
1827          */
1828         COMPARE_AND_EXCHANGE_RELEASE("compareAndExchangeRelease", AccessType.COMPARE_AND_EXCHANGE),
1829         /**
1830          * The access mode whose access is specified by the corresponding
1831          * method
1832          * {@link VarHandle#weakCompareAndSetPlain VarHandle.weakCompareAndSetPlain}
1833          */
1834         WEAK_COMPARE_AND_SET_PLAIN("weakCompareAndSetPlain", AccessType.COMPARE_AND_SET),
1835         /**
1836          * The access mode whose access is specified by the corresponding
1837          * method
1838          * {@link VarHandle#weakCompareAndSet VarHandle.weakCompareAndSet}
1839          */
1840         WEAK_COMPARE_AND_SET("weakCompareAndSet", AccessType.COMPARE_AND_SET),
1841         /**
1842          * The access mode whose access is specified by the corresponding
1843          * method
1844          * {@link VarHandle#weakCompareAndSetAcquire VarHandle.weakCompareAndSetAcquire}
1845          */
1846         WEAK_COMPARE_AND_SET_ACQUIRE("weakCompareAndSetAcquire", AccessType.COMPARE_AND_SET),
1847         /**
1848          * The access mode whose access is specified by the corresponding
1849          * method
1850          * {@link VarHandle#weakCompareAndSetRelease VarHandle.weakCompareAndSetRelease}
1851          */
1852         WEAK_COMPARE_AND_SET_RELEASE("weakCompareAndSetRelease", AccessType.COMPARE_AND_SET),
1853         /**
1854          * The access mode whose access is specified by the corresponding
1855          * method
1856          * {@link VarHandle#getAndSet VarHandle.getAndSet}
1857          */
1858         GET_AND_SET("getAndSet", AccessType.GET_AND_UPDATE),
1859         /**
1860          * The access mode whose access is specified by the corresponding
1861          * method
1862          * {@link VarHandle#getAndSetAcquire VarHandle.getAndSetAcquire}
1863          */
1864         GET_AND_SET_ACQUIRE("getAndSetAcquire", AccessType.GET_AND_UPDATE),
1865         /**
1866          * The access mode whose access is specified by the corresponding
1867          * method
1868          * {@link VarHandle#getAndSetRelease VarHandle.getAndSetRelease}
1869          */
1870         GET_AND_SET_RELEASE("getAndSetRelease", AccessType.GET_AND_UPDATE),
1871         /**
1872          * The access mode whose access is specified by the corresponding
1873          * method
1874          * {@link VarHandle#getAndAdd VarHandle.getAndAdd}
1875          */
1876         GET_AND_ADD("getAndAdd", AccessType.GET_AND_UPDATE),
1877         /**
1878          * The access mode whose access is specified by the corresponding
1879          * method
1880          * {@link VarHandle#getAndAddAcquire VarHandle.getAndAddAcquire}
1881          */
1882         GET_AND_ADD_ACQUIRE("getAndAddAcquire", AccessType.GET_AND_UPDATE),
1883         /**
1884          * The access mode whose access is specified by the corresponding
1885          * method
1886          * {@link VarHandle#getAndAddRelease VarHandle.getAndAddRelease}
1887          */
1888         GET_AND_ADD_RELEASE("getAndAddRelease", AccessType.GET_AND_UPDATE),
1889         /**
1890          * The access mode whose access is specified by the corresponding
1891          * method
1892          * {@link VarHandle#getAndBitwiseOr VarHandle.getAndBitwiseOr}
1893          */
1894         GET_AND_BITWISE_OR("getAndBitwiseOr", AccessType.GET_AND_UPDATE),
1895         /**
1896          * The access mode whose access is specified by the corresponding
1897          * method
1898          * {@link VarHandle#getAndBitwiseOrRelease VarHandle.getAndBitwiseOrRelease}
1899          */
1900         GET_AND_BITWISE_OR_RELEASE("getAndBitwiseOrRelease", AccessType.GET_AND_UPDATE),
1901         /**
1902          * The access mode whose access is specified by the corresponding
1903          * method
1904          * {@link VarHandle#getAndBitwiseOrAcquire VarHandle.getAndBitwiseOrAcquire}
1905          */
1906         GET_AND_BITWISE_OR_ACQUIRE("getAndBitwiseOrAcquire", AccessType.GET_AND_UPDATE),
1907         /**
1908          * The access mode whose access is specified by the corresponding
1909          * method
1910          * {@link VarHandle#getAndBitwiseAnd VarHandle.getAndBitwiseAnd}
1911          */
1912         GET_AND_BITWISE_AND("getAndBitwiseAnd", AccessType.GET_AND_UPDATE),
1913         /**
1914          * The access mode whose access is specified by the corresponding
1915          * method
1916          * {@link VarHandle#getAndBitwiseAndRelease VarHandle.getAndBitwiseAndRelease}
1917          */
1918         GET_AND_BITWISE_AND_RELEASE("getAndBitwiseAndRelease", AccessType.GET_AND_UPDATE),
1919         /**
1920          * The access mode whose access is specified by the corresponding
1921          * method
1922          * {@link VarHandle#getAndBitwiseAndAcquire VarHandle.getAndBitwiseAndAcquire}
1923          */
1924         GET_AND_BITWISE_AND_ACQUIRE("getAndBitwiseAndAcquire", AccessType.GET_AND_UPDATE),
1925         /**
1926          * The access mode whose access is specified by the corresponding
1927          * method
1928          * {@link VarHandle#getAndBitwiseXor VarHandle.getAndBitwiseXor}
1929          */
1930         GET_AND_BITWISE_XOR("getAndBitwiseXor", AccessType.GET_AND_UPDATE),
1931         /**
1932          * The access mode whose access is specified by the corresponding
1933          * method
1934          * {@link VarHandle#getAndBitwiseXorRelease VarHandle.getAndBitwiseXorRelease}
1935          */
1936         GET_AND_BITWISE_XOR_RELEASE("getAndBitwiseXorRelease", AccessType.GET_AND_UPDATE),
1937         /**
1938          * The access mode whose access is specified by the corresponding
1939          * method
1940          * {@link VarHandle#getAndBitwiseXorAcquire VarHandle.getAndBitwiseXorAcquire}
1941          */
1942         GET_AND_BITWISE_XOR_ACQUIRE("getAndBitwiseXorAcquire", AccessType.GET_AND_UPDATE),
1943         ;
1944 
1945         static final int COUNT = GET_AND_BITWISE_XOR_ACQUIRE.ordinal() + 1;
1946         static {
1947             assert (COUNT == values().length);
1948         }
1949         final String methodName;
1950         final AccessType at;
1951 
1952         AccessMode(final String methodName, AccessType at) {
1953             this.methodName = methodName;
1954             this.at = at;
1955         }
1956 
1957         /**
1958          * Returns the {@code VarHandle} signature-polymorphic method name
1959          * associated with this {@code AccessMode} value.
1960          *
1961          * @return the signature-polymorphic method name
1962          * @see #valueFromMethodName
1963          */
1964         public String methodName() {
1965             return methodName;
1966         }
1967 
1968         /**
1969          * Returns the {@code AccessMode} value associated with the specified
1970          * {@code VarHandle} signature-polymorphic method name.
1971          *
1972          * @param methodName the signature-polymorphic method name
1973          * @return the {@code AccessMode} value
1974          * @throws IllegalArgumentException if there is no {@code AccessMode}
1975          *         value associated with method name (indicating the method
1976          *         name does not correspond to a {@code VarHandle}
1977          *         signature-polymorphic method name).
1978          * @see #methodName()
1979          */
1980         public static AccessMode valueFromMethodName(String methodName) {
1981             return switch (methodName) {
1982                 case "get" -> GET;
1983                 case "set" -> SET;
1984                 case "getVolatile" -> GET_VOLATILE;
1985                 case "setVolatile" -> SET_VOLATILE;
1986                 case "getAcquire" -> GET_ACQUIRE;
1987                 case "setRelease" -> SET_RELEASE;
1988                 case "getOpaque" -> GET_OPAQUE;
1989                 case "setOpaque" -> SET_OPAQUE;
1990                 case "compareAndSet" -> COMPARE_AND_SET;
1991                 case "compareAndExchange" -> COMPARE_AND_EXCHANGE;
1992                 case "compareAndExchangeAcquire" -> COMPARE_AND_EXCHANGE_ACQUIRE;
1993                 case "compareAndExchangeRelease" -> COMPARE_AND_EXCHANGE_RELEASE;
1994                 case "weakCompareAndSet" -> WEAK_COMPARE_AND_SET;
1995                 case "weakCompareAndSetPlain" -> WEAK_COMPARE_AND_SET_PLAIN;
1996                 case "weakCompareAndSetAcquire" -> WEAK_COMPARE_AND_SET_ACQUIRE;
1997                 case "weakCompareAndSetRelease" -> WEAK_COMPARE_AND_SET_RELEASE;
1998                 case "getAndSet" -> GET_AND_SET;
1999                 case "getAndSetAcquire" -> GET_AND_SET_ACQUIRE;
2000                 case "getAndSetRelease" -> GET_AND_SET_RELEASE;
2001                 case "getAndAdd" -> GET_AND_ADD;
2002                 case "getAndAddAcquire" -> GET_AND_ADD_ACQUIRE;
2003                 case "getAndAddRelease" -> GET_AND_ADD_RELEASE;
2004                 case "getAndBitwiseOr" -> GET_AND_BITWISE_OR;
2005                 case "getAndBitwiseOrRelease" -> GET_AND_BITWISE_OR_RELEASE;
2006                 case "getAndBitwiseOrAcquire" -> GET_AND_BITWISE_OR_ACQUIRE;
2007                 case "getAndBitwiseAnd" -> GET_AND_BITWISE_AND;
2008                 case "getAndBitwiseAndRelease" -> GET_AND_BITWISE_AND_RELEASE;
2009                 case "getAndBitwiseAndAcquire" -> GET_AND_BITWISE_AND_ACQUIRE;
2010                 case "getAndBitwiseXor" -> GET_AND_BITWISE_XOR;
2011                 case "getAndBitwiseXorRelease" -> GET_AND_BITWISE_XOR_RELEASE;
2012                 case "getAndBitwiseXorAcquire" -> GET_AND_BITWISE_XOR_ACQUIRE;
2013                 default -> throw new IllegalArgumentException("No AccessMode value for method name " + methodName);
2014             };
2015         }
2016 
2017         private static final @Stable AccessMode[] VALUES = values();
2018         static AccessMode valueFromOrdinal(int mode) {
2019             return VALUES[mode];
2020         }
2021     }
2022 
2023     static final class AccessDescriptor {
2024         final MethodType symbolicMethodTypeExact;
2025         final MethodType symbolicMethodTypeErased;
2026         final MethodType symbolicMethodTypeInvoker;
2027         final Class<?> returnType;
2028         final int type;
2029         final int mode;
2030 
2031         public AccessDescriptor(MethodType symbolicMethodType, int type, int mode) {
2032             this.symbolicMethodTypeExact = symbolicMethodType;
2033             this.symbolicMethodTypeErased = symbolicMethodType.erase();
2034             this.symbolicMethodTypeInvoker = symbolicMethodType.insertParameterTypes(0, VarHandle.class);
2035             this.returnType = symbolicMethodType.returnType();
2036             this.type = type;
2037             this.mode = mode;
2038         }
2039     }
2040 
2041     /**
2042      * Returns a compact textual description of this {@linkplain VarHandle},
2043      * including the type of variable described, and a description of its coordinates.
2044      *
2045      * @return A compact textual description of this {@linkplain VarHandle}
2046      */
2047     @Override
2048     public final String toString() {
2049         return String.format("VarHandle[varType=%s, coord=%s]",
2050                              varType().getName(),
2051                              coordinateTypes());
2052     }
2053 
2054     /**
2055      * Returns the variable type of variables referenced by this VarHandle.
2056      *
2057      * @return the variable type of variables referenced by this VarHandle
2058      */
2059     public Class<?> varType() {
2060         MethodType typeSet = accessModeType(AccessMode.SET);
2061         return typeSet.parameterType(typeSet.parameterCount() - 1);
2062     }
2063 
2064     /**
2065      * Returns the coordinate types for this VarHandle.
2066      *
2067      * @return the coordinate types for this VarHandle. The returned
2068      * list is unmodifiable
2069      */
2070     public List<Class<?>> coordinateTypes() {
2071         MethodType typeGet = accessModeType(AccessMode.GET);
2072         return typeGet.parameterList();
2073     }
2074 
2075     /**
2076      * Obtains the access mode type for this VarHandle and a given access mode.
2077      *
2078      * <p>The access mode type's parameter types will consist of a prefix that
2079      * is the coordinate types of this VarHandle followed by further
2080      * types as defined by the access mode method.
2081      * The access mode type's return type is defined by the return type of the
2082      * access mode method.
2083      *
2084      * @param accessMode the access mode, corresponding to the
2085      * signature-polymorphic method of the same name
2086      * @return the access mode type for the given access mode
2087      */
2088     public final MethodType accessModeType(AccessMode accessMode) {
2089         return accessModeType(accessMode.at.ordinal());
2090     }
2091 
2092     /**
2093      * Validates that the given access descriptors method type matches up with
2094      * the access mode of this VarHandle, then returns if this is direct.
2095      * These operations were grouped together to slightly
2096      * improve efficiency during startup/warmup.
2097      *
2098      * A direct VarHandle's VarForm has implementation MemberNames that can
2099      * be linked directly. If a VarHandle is indirect, it must override
2100      * {@link #isAccessModeSupported} and {@link #getMethodHandleUncached}
2101      * which access MemberNames.
2102      *
2103      * @return true if this is a direct VarHandle, false if it's an indirect
2104      *         VarHandle.
2105      * @throws WrongMethodTypeException if there's an access type mismatch
2106      * @see #asDirect()
2107      */
2108     @ForceInline
2109     boolean checkAccessModeThenIsDirect(VarHandle.AccessDescriptor ad) {
2110         if (exact && accessModeType(ad.type) != ad.symbolicMethodTypeExact) {
2111             throwWrongMethodTypeException(ad);
2112         }
2113         // return true unless overridden in an IndirectVarHandle
2114         return true;
2115     }
2116 
2117     @DontInline
2118     private final void throwWrongMethodTypeException(VarHandle.AccessDescriptor ad) {
2119         throw new WrongMethodTypeException("handle's method type " + accessModeType(ad.type)
2120                 + " but found " + ad.symbolicMethodTypeExact);
2121     }
2122 
2123     @ForceInline
2124     final MethodType accessModeType(int accessTypeOrdinal) {
2125         MethodType[] mtTable = methodTypeTable;
2126         if (mtTable == null) {
2127             mtTable = methodTypeTable = new MethodType[VarHandle.AccessType.COUNT];
2128         }
2129         MethodType mt = mtTable[accessTypeOrdinal];
2130         if (mt == null) {
2131             mt = mtTable[accessTypeOrdinal] =
2132                     accessModeTypeUncached(accessTypeOrdinal);
2133         }
2134         return mt;
2135     }
2136 
2137     final MethodType accessModeTypeUncached(int accessTypeOrdinal) {
2138         return accessModeTypeUncached(AccessType.values()[accessTypeOrdinal]);
2139     }
2140 
2141     abstract MethodType accessModeTypeUncached(AccessType accessMode);
2142 
2143     /**
2144      * Returns {@code true} if the given access mode is supported, otherwise
2145      * {@code false}.
2146      *
2147      * <p>The return of a {@code false} value for a given access mode indicates
2148      * that an {@code UnsupportedOperationException} is thrown on invocation
2149      * of the corresponding access mode method.
2150      *
2151      * @param accessMode the access mode, corresponding to the
2152      * signature-polymorphic method of the same name
2153      * @return {@code true} if the given access mode is supported, otherwise
2154      * {@code false}.
2155      */
2156     public boolean isAccessModeSupported(AccessMode accessMode) {
2157         return vform.getMemberNameOrNull(accessMode.ordinal()) != null;
2158     }
2159 
2160     /**
2161      * Obtains a method handle bound to this VarHandle and the given access
2162      * mode.
2163      *
2164      * @apiNote This method, for a VarHandle {@code vh} and access mode
2165      * {@code {access-mode}}, returns a method handle that is equivalent to
2166      * method handle {@code bmh} in the following code (though it may be more
2167      * efficient):
2168      * <pre>{@code
2169      * MethodHandle mh = MethodHandles.varHandleExactInvoker(
2170      *                       vh.accessModeType(VarHandle.AccessMode.{access-mode}));
2171      *
2172      * MethodHandle bmh = mh.bindTo(vh);
2173      * }</pre>
2174      *
2175      * @param accessMode the access mode, corresponding to the
2176      * signature-polymorphic method of the same name
2177      * @return a method handle bound to this VarHandle and the given access mode
2178      */
2179     public MethodHandle toMethodHandle(AccessMode accessMode) {
2180         if (isAccessModeSupported(accessMode)) {
2181             MethodHandle mh = getMethodHandle(accessMode.ordinal());
2182             return mh.bindTo(asDirect());
2183         }
2184         else {
2185             // Ensure an UnsupportedOperationException is thrown
2186             return MethodHandles.varHandleInvoker(accessMode, accessModeType(accessMode)).
2187                     bindTo(this);
2188         }
2189     }
2190 
2191     /**
2192      * Return a nominal descriptor for this instance, if one can be
2193      * constructed, or an empty {@link Optional} if one cannot be.
2194      *
2195      * @return An {@link Optional} containing the resulting nominal descriptor,
2196      * or an empty {@link Optional} if one cannot be constructed.
2197      * @since 12
2198      */
2199     @Override
2200     public Optional<VarHandleDesc> describeConstable() {
2201         // partial function for field and array only
2202         return Optional.empty();
2203     }
2204 
2205     @Stable
2206     MethodType[] methodTypeTable;
2207 
2208     @Stable
2209     MethodHandle[] methodHandleTable;
2210 
2211     @ForceInline
2212     final MethodHandle getMethodHandle(int mode) {
2213         MethodHandle[] mhTable = methodHandleTable;
2214         if (mhTable == null) {
2215             mhTable = methodHandleTable = new MethodHandle[AccessMode.COUNT];
2216         }
2217         MethodHandle mh = mhTable[mode];
2218         if (mh == null) {
2219             mh = mhTable[mode] = getMethodHandleUncached(mode);
2220         }
2221         return mh;
2222     }
2223 
2224     /**
2225      * Computes a method handle that can be passed the {@linkplain #asDirect() direct}
2226      * var handle of this var handle with the given access mode. Pre/postprocessing
2227      * such as argument or return value filtering should be done by the returned
2228      * method handle.
2229      *
2230      * @throws UnsupportedOperationException if the access mode is not supported
2231      */
2232     MethodHandle getMethodHandleUncached(int mode) {
2233         MethodType mt = accessModeType(AccessMode.valueFromOrdinal(mode)).
2234                 insertParameterTypes(0, VarHandle.class);
2235         MemberName mn = vform.getMemberName(mode);
2236         DirectMethodHandle dmh = DirectMethodHandle.make(mn);
2237         // Such a method handle must not be publicly exposed directly
2238         // otherwise it can be cracked, it must be transformed or rebound
2239         // before exposure
2240         MethodHandle mh = dmh.copyWith(mt, dmh.form);
2241         assert mh.type().erase() == mn.getMethodType().erase();
2242         return mh;
2243     }
2244 
2245 
2246     /*non-public*/
2247     final void updateVarForm(VarForm newVForm) {
2248         if (vform == newVForm) return;
2249         UNSAFE.putReference(this, VFORM_OFFSET, newVForm);
2250         UNSAFE.fullFence();
2251     }
2252 
2253     private static final long VFORM_OFFSET;
2254 
2255     static {
2256         VFORM_OFFSET = UNSAFE.objectFieldOffset(VarHandle.class, "vform");
2257 
2258         // The VarHandleGuards must be initialized to ensure correct
2259         // compilation of the guard methods
2260         UNSAFE.ensureClassInitialized(VarHandleGuards.class);
2261     }
2262 
2263 
2264     // Fence methods
2265 
2266     /**
2267      * Ensures that loads and stores before the fence will not be reordered
2268      * with
2269      * loads and stores after the fence.
2270      *
2271      * @apiNote Ignoring the many semantic differences from C and C++, this
2272      * method has memory ordering effects compatible with
2273      * {@code atomic_thread_fence(memory_order_seq_cst)}
2274      */
2275     @ForceInline
2276     public static void fullFence() {
2277         UNSAFE.fullFence();
2278     }
2279 
2280     /**
2281      * Ensures that loads before the fence will not be reordered with loads and
2282      * stores after the fence.
2283      *
2284      * @apiNote Ignoring the many semantic differences from C and C++, this
2285      * method has memory ordering effects compatible with
2286      * {@code atomic_thread_fence(memory_order_acquire)}
2287      */
2288     @ForceInline
2289     public static void acquireFence() {
2290         UNSAFE.loadFence();
2291     }
2292 
2293     /**
2294      * Ensures that loads and stores before the fence will not be
2295      * reordered with stores after the fence.
2296      *
2297      * @apiNote Ignoring the many semantic differences from C and C++, this
2298      * method has memory ordering effects compatible with
2299      * {@code atomic_thread_fence(memory_order_release)}
2300      */
2301     @ForceInline
2302     public static void releaseFence() {
2303         UNSAFE.storeFence();
2304     }
2305 
2306     /**
2307      * Ensures that loads before the fence will not be reordered with
2308      * loads after the fence.
2309      */
2310     @ForceInline
2311     public static void loadLoadFence() {
2312         UNSAFE.loadLoadFence();
2313     }
2314 
2315     /**
2316      * Ensures that stores before the fence will not be reordered with
2317      * stores after the fence.
2318      */
2319     @ForceInline
2320     public static void storeStoreFence() {
2321         UNSAFE.storeStoreFence();
2322     }
2323 
2324     /**
2325      * A <a href="{@docRoot}/java.base/java/lang/constant/package-summary.html#nominal">nominal descriptor</a> for a
2326      * {@link VarHandle} constant.
2327      *
2328      * @since 12
2329      */
2330     public static final class VarHandleDesc extends DynamicConstantDesc<VarHandle> {
2331 
2332         /**
2333          * Kinds of variable handle descs
2334          */
2335         private enum Kind {
2336             FIELD(ConstantDescs.BSM_VARHANDLE_FIELD),
2337             STATIC_FIELD(ConstantDescs.BSM_VARHANDLE_STATIC_FIELD),
2338             ARRAY(ConstantDescs.BSM_VARHANDLE_ARRAY);
2339 
2340             final DirectMethodHandleDesc bootstrapMethod;
2341 
2342             Kind(DirectMethodHandleDesc bootstrapMethod) {
2343                 this.bootstrapMethod = bootstrapMethod;
2344             }
2345 
2346             ConstantDesc[] toBSMArgs(ClassDesc declaringClass, ClassDesc varType) {
2347                 return switch (this) {
2348                     case FIELD, STATIC_FIELD -> new ConstantDesc[]{declaringClass, varType};
2349                     case ARRAY               -> new ConstantDesc[]{declaringClass};
2350                     default -> throw new InternalError("Cannot reach here");
2351                 };
2352             }
2353         }
2354 
2355         private final Kind kind;
2356         private final ClassDesc declaringClass;
2357         private final ClassDesc varType;
2358 
2359         /**
2360          * Construct a {@linkplain VarHandleDesc} given a kind, name, and declaring
2361          * class.
2362          *
2363          * @param kind the kind of the var handle
2364          * @param name the unqualified name of the field, for field var handles; otherwise ignored
2365          * @param declaringClass a {@link ClassDesc} describing the declaring class,
2366          *                       for field var handles
2367          * @param varType a {@link ClassDesc} describing the type of the variable
2368          * @throws NullPointerException if any required argument is null
2369          * @jvms 4.2.2 Unqualified Names
2370          */
2371         private VarHandleDesc(Kind kind, String name, ClassDesc declaringClass, ClassDesc varType) {
2372             super(kind.bootstrapMethod, name,
2373                   ConstantDescs.CD_VarHandle,
2374                   kind.toBSMArgs(declaringClass, varType));
2375             this.kind = kind;
2376             this.declaringClass = declaringClass;
2377             this.varType = varType;
2378         }
2379 
2380         /**
2381          * Returns a {@linkplain VarHandleDesc} corresponding to a {@link VarHandle}
2382          * for an instance field.
2383          *
2384          * @param name the unqualified name of the field
2385          * @param declaringClass a {@link ClassDesc} describing the declaring class,
2386          *                       for field var handles
2387          * @param fieldType a {@link ClassDesc} describing the type of the field
2388          * @return the {@linkplain VarHandleDesc}
2389          * @throws NullPointerException if any of the arguments are null
2390          * @jvms 4.2.2 Unqualified Names
2391          */
2392         public static VarHandleDesc ofField(ClassDesc declaringClass, String name, ClassDesc fieldType) {
2393             Objects.requireNonNull(declaringClass);
2394             Objects.requireNonNull(name);
2395             Objects.requireNonNull(fieldType);
2396             return new VarHandleDesc(Kind.FIELD, name, declaringClass, fieldType);
2397         }
2398 
2399         /**
2400          * Returns a {@linkplain VarHandleDesc} corresponding to a {@link VarHandle}
2401          * for a static field.
2402          *
2403          * @param name the unqualified name of the field
2404          * @param declaringClass a {@link ClassDesc} describing the declaring class,
2405          *                       for field var handles
2406          * @param fieldType a {@link ClassDesc} describing the type of the field
2407          * @return the {@linkplain VarHandleDesc}
2408          * @throws NullPointerException if any of the arguments are null
2409          * @jvms 4.2.2 Unqualified Names
2410          */
2411         public static VarHandleDesc ofStaticField(ClassDesc declaringClass, String name, ClassDesc fieldType) {
2412             Objects.requireNonNull(declaringClass);
2413             Objects.requireNonNull(name);
2414             Objects.requireNonNull(fieldType);
2415             return new VarHandleDesc(Kind.STATIC_FIELD, name, declaringClass, fieldType);
2416         }
2417 
2418         /**
2419          * Returns a {@linkplain VarHandleDesc} corresponding to a {@link VarHandle}
2420          * for an array type.
2421          *
2422          * @param arrayClass a {@link ClassDesc} describing the type of the array
2423          * @return the {@linkplain VarHandleDesc}
2424          * @throws NullPointerException if any of the arguments are null
2425          */
2426         public static VarHandleDesc ofArray(ClassDesc arrayClass) {
2427             Objects.requireNonNull(arrayClass);
2428             if (!arrayClass.isArray())
2429                 throw new IllegalArgumentException("Array class argument not an array: " + arrayClass);
2430             return new VarHandleDesc(Kind.ARRAY, ConstantDescs.DEFAULT_NAME, arrayClass, arrayClass.componentType());
2431         }
2432 
2433         /**
2434          * Returns a {@link ClassDesc} describing the type of the variable described
2435          * by this descriptor.
2436          *
2437          * @return the variable type
2438          */
2439         public ClassDesc varType() {
2440             return varType;
2441         }
2442 
2443         @Override
2444         public VarHandle resolveConstantDesc(MethodHandles.Lookup lookup)
2445                 throws ReflectiveOperationException {
2446             return switch (kind) {
2447                 case FIELD        -> lookup.findVarHandle(declaringClass.resolveConstantDesc(lookup),
2448                                                           constantName(),
2449                                                           varType.resolveConstantDesc(lookup));
2450                 case STATIC_FIELD -> lookup.findStaticVarHandle(declaringClass.resolveConstantDesc(lookup),
2451                                                           constantName(),
2452                                                           varType.resolveConstantDesc(lookup));
2453                 case ARRAY        -> MethodHandles.arrayElementVarHandle(declaringClass.resolveConstantDesc(lookup));
2454                 default -> throw new InternalError("Cannot reach here");
2455             };
2456         }
2457 
2458         /**
2459          * Returns a compact textual description of this constant description.
2460          * For a field {@linkplain VarHandle}, includes the owner, name, and type
2461          * of the field, and whether it is static; for an array {@linkplain VarHandle},
2462          * the name of the component type.
2463          *
2464          * @return A compact textual description of this descriptor
2465          */
2466         @Override
2467         public String toString() {
2468             return switch (kind) {
2469                 case FIELD, STATIC_FIELD -> String.format("VarHandleDesc[%s%s.%s:%s]",
2470                                                            (kind == Kind.STATIC_FIELD) ? "static " : "",
2471                                                            declaringClass.displayName(), constantName(), varType.displayName());
2472                 case ARRAY               -> String.format("VarHandleDesc[%s[]]", declaringClass.displayName());
2473                 default -> throw new InternalError("Cannot reach here");
2474             };
2475         }
2476     }
2477 
2478 }