VarHandle (Java SE 9 & JDK 9 ) (original) (raw)

public abstract class VarHandle
extends Object
A VarHandle is a dynamically strongly typed reference to a variable, or to a parametrically-defined family of variables, including static fields, non-static fields, array elements, or components of an off-heap data structure. Access to such variables is supported under various_access modes_, including plain read/write access, volatile read/write access, and compare-and-swap.
VarHandles are immutable and have no visible state. VarHandles cannot be subclassed by the user.
A VarHandle has:

Compiling invocation of access mode methods

A Java method call expression naming an access mode method can invoke a VarHandle from Java source code. From the viewpoint of source code, these methods can take any arguments and their polymorphic result (if expressed) can be cast to any return type. Formally this is accomplished by giving the access mode methods variable arity Object arguments andObject return types (if the return type is polymorphic), but they have an additional quality called signature polymorphism which connects this freedom of invocation directly to the JVM execution stack.
As is usual with virtual methods, source-level calls to access mode methods compile to an invokevirtual instruction. More unusually, the compiler must record the actual argument types, and may not perform method invocation conversions on the arguments. Instead, it must generate instructions to push them on the stack according to their own unconverted types. The VarHandle object itself will be pushed on the stack before the arguments. The compiler then generates an invokevirtual instruction that invokes the access mode method with a symbolic type descriptor which describes the argument and return types.
To issue a complete symbolic type descriptor, the compiler must also determine the return type (if polymorphic). This is based on a cast on the method invocation expression, if there is one, or else Object if the invocation is an expression, or else void if the invocation is a statement. The cast may be to a primitive type (but not void).
As a corner case, an uncasted null argument is given a symbolic type descriptor of java.lang.Void. The ambiguity with the typeVoid is harmless, since there are no references of type Void except the null reference.

Performing invocation of access mode methods

The first time an invokevirtual instruction is executed it is linked by symbolically resolving the names in the instruction and verifying that the method call is statically legal. This also holds for calls to access mode methods. In this case, the symbolic type descriptor emitted by the compiler is checked for correct syntax, and names it contains are resolved. Thus, aninvokevirtual instruction which invokes an access mode method will always link, as long as the symbolic type descriptor is syntactically well-formed and the types exist.
When the invokevirtual is executed after linking, the receiving VarHandle's access mode type is first checked by the JVM to ensure that it matches the symbolic type descriptor. If the type match fails, it means that the access mode method which the caller is invoking is not present on the individual VarHandle being invoked.
Invocation of an access mode method behaves as if an invocation ofMethodHandle.invoke(java.lang.Object...), where the receiving method handle accepts the VarHandle instance as the leading argument. More specifically, the following, where {access-mode} corresponds to the access mode method name:
VarHandle vh = .. R r = (R) vh.{access-mode}(p1, p2, ..., pN);
behaves as if:
VarHandle vh = .. VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}"); MethodHandle mh = MethodHandles.varHandleExactInvoker( am, vh.accessModeType(am)); R r = (R) mh.invoke(vh, p1, p2, ..., pN)
(modulo access mode methods do not declare throwing of Throwable). This is equivalent to:
MethodHandle mh = MethodHandles.lookup().findVirtual( VarHandle.class, "{access-mode}", MethodType.methodType(R, p1, p2, ..., pN)); R r = (R) mh.invokeExact(vh, p1, p2, ..., pN)
where the desired method type is the symbolic type descriptor and aMethodHandle.invokeExact(java.lang.Object...) is performed, since before invocation of the target, the handle will apply reference casts as necessary and box, unbox, or widen primitive values, as if by asType (see alsoMethodHandles.varHandleInvoker(java.lang.invoke.VarHandle.AccessMode, java.lang.invoke.MethodType)). More concisely, such behaviour is equivalent to:
VarHandle vh = .. VarHandle.AccessMode am = VarHandle.AccessMode.valueFromMethodName("{access-mode}"); MethodHandle mh = vh.toMethodHandle(am); R r = (R) mh.invoke(p1, p2, ..., pN)
Where, in this case, the method handle is bound to the VarHandle instance.

Invocation checking

In typical programs, VarHandle access mode type matching will usually succeed. But if a match fails, the JVM will throw aWrongMethodTypeException.
Thus, an access mode type mismatch which might show up as a linkage error in a statically typed program can show up as a dynamicWrongMethodTypeException in a program which uses VarHandles.
Because access mode types contain "live" Class objects, method type matching takes into account both type names and class loaders. Thus, even if a VarHandle VH is created in one class loaderL1 and used in another L2, VarHandle access mode method calls are type-safe, because the caller's symbolic type descriptor, as resolved in L2, is matched against the original callee method's symbolic type descriptor, as resolved in L1. The resolution inL1 happens when VH is created and its access mode types are assigned, while the resolution in L2 happens when theinvokevirtual instruction is linked.
Apart from type descriptor checks, a VarHandles's capability to access it's variables is unrestricted. If a VarHandle is formed on a non-public variable by a class that has access to that variable, the resulting VarHandle can be used in any place by any caller who receives a reference to it.
Unlike with the Core Reflection API, where access is checked every time a reflective method is invoked, VarHandle access checking is performedwhen the VarHandle is created. Thus, VarHandles to non-public variables, or to variables in non-public classes, should generally be kept secret. They should not be passed to untrusted code unless their use from the untrusted code would be harmless.

VarHandle creation

Java code can create a VarHandle that directly accesses any field that is accessible to that code. This is done via a reflective, capability-based API called MethodHandles.Lookup. For example, a VarHandle for a non-static field can be obtained from Lookup.findVarHandle. There is also a conversion method from Core Reflection API objects,Lookup.unreflectVarHandle.
Access to protected field members is restricted to receivers only of the accessing class, or one of its subclasses, and the accessing class must in turn be a subclass (or package sibling) of the protected member's defining class. If a VarHandle refers to a protected non-static field of a declaring class outside the current package, the receiver argument will be narrowed to the type of the accessing class.

Interoperation between VarHandles and the Core Reflection API

Using factory methods in the Lookup API, any field represented by a Core Reflection API object can be converted to a behaviorally equivalent VarHandle. For example, a reflective Field can be converted to a VarHandle usingLookup.unreflectVarHandle. The resulting VarHandles generally provide more direct and efficient access to the underlying fields.
As a special case, when the Core Reflection API is used to view the signature polymorphic access mode methods in this class, they appear as ordinary non-polymorphic methods. Their reflective appearance, as viewed byClass.getDeclaredMethod, is unaffected by their special status in this API. For example, Method.getModifiers will report exactly those modifier bits required for any similarly declared method, including in this case native and varargs bits.
As with any reflected method, these methods (when reflected) may be invoked directly via java.lang.reflect.Method.invoke, via JNI, or indirectly viaLookup.unreflect. However, such reflective calls do not result in access mode method invocations. Such a call, if passed the required argument (a single one, of type Object[]), will ignore the argument and will throw anUnsupportedOperationException.
Since invokevirtual instructions can natively invoke VarHandle access mode methods under any symbolic type descriptor, this reflective view conflicts with the normal presentation of these methods via bytecodes. Thus, these native methods, when reflectively viewed byClass.getDeclaredMethod, may be regarded as placeholders only.
In order to obtain an invoker method for a particular access mode type, use MethodHandles.varHandleExactInvoker(java.lang.invoke.VarHandle.AccessMode, java.lang.invoke.MethodType) orMethodHandles.varHandleInvoker(java.lang.invoke.VarHandle.AccessMode, java.lang.invoke.MethodType). TheLookup.findVirtual API is also able to return a method handle to call an access mode method for any specified access mode type and is equivalent in behaviour toMethodHandles.varHandleInvoker(java.lang.invoke.VarHandle.AccessMode, java.lang.invoke.MethodType).

Interoperation between VarHandles and Java generics

A VarHandle can be obtained for a variable, such as a a field, which is declared with Java generic types. As with the Core Reflection API, the VarHandle's variable type will be constructed from the erasure of the source-level type. When a VarHandle access mode method is invoked, the types of its arguments or the return value cast type may be generic types or type instances. If this occurs, the compiler will replace those types by their erasures when it constructs the symbolic type descriptor for theinvokevirtual instruction.
Since:
9
See Also:
MethodHandle, MethodHandles, MethodType