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