Package java.lang.invoke


packagejava.lang.invoke
Thejava.lang.invoke package provides low-level primitives for interactingwith the Java Virtual Machine.

As described in the Java Virtual Machine Specification, certain types in this packageare given special treatment by the virtual machine:

  • The classesMethodHandle andVarHandle containsignature polymorphic methodswhich can be linked regardless of their type descriptor.Normally, method linkage requires exact matching of type descriptors.
  • The JVM bytecode format supports immediate constants ofthe classesMethodHandle andMethodType.
  • Theinvokedynamic instruction makes use of bootstrapMethodHandleconstants to dynamically resolveCallSite objects for custom method invocationbehavior.
  • Theldc instruction makes use of bootstrapMethodHandle constantsto dynamically resolve custom constant values.

Dynamic resolution of call sites and constants

The following low-level information summarizes relevant parts of theJava Virtual Machine specification. For full details, please see thecurrent version of that specification.

Dynamically-computed call sites

Aninvokedynamic instruction is originally in an unlinked state.In this state, there is no target method for the instruction to invoke.

Before the JVM can execute aninvokedynamic instruction,the instruction must first belinked.Linking is accomplished by calling abootstrap methodwhich is given the static information content of the call,and which must produce aCallSitethat gives the behavior of the invocation.

Eachinvokedynamic instruction statically specifies its ownbootstrap method as a constant pool reference.The constant pool reference also specifies the invocation's name and method type descriptor,just likeinvokestatic and the other invoke instructions.

Dynamically-computed constants

The constant pool may contain constants taggedCONSTANT_Dynamic,equipped with bootstrap methods which perform their resolution.Such adynamic constant is originally in an unresolved state.Before the JVM can use a dynamically-computed constant, it must first beresolved.Dynamically-computed constant resolution is accomplished by calling abootstrap methodwhich is given the static information content of the constant,and which must produce a value of the constant's statically declared type.

Each dynamically-computed constant statically specifies its ownbootstrap method as a constant pool reference.The constant pool reference also specifies the constant's name and field type descriptor,just likegetstatic and the other field reference instructions.(Roughly speaking, a dynamically-computed constant is to a dynamically-computed call siteas aCONSTANT_Fieldref is to aCONSTANT_Methodref.)

Execution of bootstrap methods

Resolving a dynamically-computed call site or constantstarts with resolving constants from the constant pool for thefollowing items:
  • the bootstrap method, aCONSTANT_MethodHandle
  • theClass orMethodType derived fromtype component of theCONSTANT_NameAndType descriptor
  • static arguments, if any (note that static arguments can themselves bedynamically-computed constants)

The bootstrap method is then invoked, as if byMethodHandle.invoke,with the following arguments:

  • aMethodHandles.Lookup, which is a lookup object on thecaller classin which dynamically-computed constant or call site occurs
  • aString, the name mentioned in theCONSTANT_NameAndType
  • aMethodType orClass, the resolved type descriptor of theCONSTANT_NameAndType
  • aClass, the resolved type descriptor of the constant, if it is a dynamic constant
  • the additional resolved static arguments, if any

For a dynamically-computed call site, the returned result must be a non-null reference to aCallSite.The type of the call site's target must be exactly equal to the typederived from the invocation's type descriptor and passed tothe bootstrap method. If these conditions are not met, aBootstrapMethodError is thrown.On success the call site then becomes permanently linked to theinvokedynamicinstruction.

For a dynamically-computed constant, the first parameter of the bootstrapmethod must be assignable toMethodHandles.Lookup. If this conditionis not met, aBootstrapMethodError is thrown.On success the result of the bootstrap method is cached as the resolvedconstant value.

If an exception,E say, occurs during execution of the bootstrap method, thenresolution fails and terminates abnormally.E is rethrown if the type ofE isError or a subclass, otherwise aBootstrapMethodError that wrapsE is thrown.If this happens, the same error will be thrown for allsubsequent attempts to execute theinvokedynamic instruction or load thedynamically-computed constant.

Timing of resolution

Aninvokedynamic instruction is linked just before its first execution.A dynamically-computed constant is resolved just before the first time it is used(by pushing it on the stack or linking it as a bootstrap method parameter).The bootstrap method call implementing the linkage occurs withina thread that is attempting a first execution or first use.

If there are several such threads, the bootstrap method may beinvoked in several threads concurrently.Therefore, bootstrap methods which access global applicationdata must take the usual precautions against race conditions.In any case, everyinvokedynamic instruction is eitherunlinked or linked to a uniqueCallSite object.

In an application which requiresinvokedynamic instructions with individuallymutable behaviors, their bootstrap methods should produce distinctCallSite objects, one for each linkage request.Alternatively, an application can link a singleCallSite objectto severalinvokedynamic instructions, in which casea change to the target method will become visible at each ofthe instructions.

If several threads simultaneously execute a bootstrap method for a single dynamically-computedcall site or constant, the JVM must choose one bootstrap method result and install it visibly toall threads. Any other bootstrap method calls are allowed to complete, but theirresults are ignored.

Discussion:These rules do not enable the JVM to share call sites,or to issue “causeless” bootstrap method calls.Everyinvokedynamic instruction transitions at most once from unlinked to linked,just before its first invocation.There is no way to undo the effect of a completed bootstrap method call.

Types of bootstrap methods

For a dynamically-computed call site, the bootstrap method is invoked with parametertypesMethodHandles.Lookup,String,MethodType, and the typesof any static arguments; the return type isCallSite.

For a dynamically-computed constant, the bootstrap method is invoked with parameter typesMethodHandles.Lookup,String,Class, and the types of anystatic arguments; the return type is the type represented by theClass.

BecauseMethodHandle.invoke allows foradaptations between the invoked method type and the bootstrap method handle's method type,there is flexibility in the declaration of the bootstrap method.For a dynamically-computed constant the first parameter type of the bootstrap method handlemust be assignable toMethodHandles.Lookup, other than that constraint the same degreeof flexibility applies to bootstrap methods of dynamically-computed call sites anddynamically-computed constants.Note: this constraint allows for the future possibility where the bootstrap method isinvoked with just the parameter types of static arguments, thereby supporting a widerrange of methods compatible with the static arguments (such as methods that don't declareor require the lookup, name, and type meta-data parameters).

For example, for dynamically-computed call site, the first argumentcould beObject instead ofMethodHandles.Lookup, and the return typecould also beObject instead ofCallSite.(Note that the types and number of the stacked arguments limitthe legal kinds of bootstrap methods to appropriately typedstatic methods and constructors.)

If a pushed value is a primitive type, it may be converted to a reference by boxing conversion.If the bootstrap method is a variable arity method (its modifier bit0x0080 is set),then some or all of the arguments specified here may be collected into a trailing array parameter.(This is not a special rule, but rather a useful consequence of the interactionbetweenCONSTANT_MethodHandle constants, the modifier bit for variable arity methods,and theasVarargsCollector transformation.)

Given these rules, here are examples of legal bootstrap method declarations fordynamically-computed call sites, given various numbersN of extra arguments.The first row (marked*) will work for any number of extra arguments.

Static argument types
NSample bootstrap method
*
  • CallSite bootstrap(Lookup caller, String name, MethodType type, Object... args)
  • CallSite bootstrap(Object... args)
  • CallSite bootstrap(Object caller, Object... nameAndTypeWithArgs)
0
  • CallSite bootstrap(Lookup caller, String name, MethodType type)
  • CallSite bootstrap(Lookup caller, Object... nameAndType)
1CallSite bootstrap(Lookup caller, String name, MethodType type, Object arg)
2
  • CallSite bootstrap(Lookup caller, String name, MethodType type, Object... args)
  • CallSite bootstrap(Lookup caller, String name, MethodType type, String... args)
  • CallSite bootstrap(Lookup caller, String name, MethodType type, String x, int y)
The last example assumes that the extra arguments are of typeString andInteger (orint), respectively.The second-to-last example assumes that all extra arguments are of typeString.The other examples work with all types of extra arguments. Note that allthe examples except the second and third also work with dynamically-computedconstants if the return type is changed to be compatible with theconstant's declared type (such asObject, which is always compatible).

Since dynamically-computed constants can be provided as static arguments to bootstrapmethods, there are no limitations on the types of bootstrap arguments.However, arguments of typeboolean,byte,short, orcharcannot bedirectly supplied byCONSTANT_Integerconstant pool entries, since theasType conversions donot perform the necessary narrowing primitive conversions.

In the above examples, the return type is alwaysCallSite,but that is not a necessary feature of bootstrap methods.In the case of a dynamically-computed call site, the only requirement is thatthe return type of the bootstrap method must be convertible(using theasType conversions) toCallSite, whichmeans the bootstrap method return type might beObject orConstantCallSite.In the case of a dynamically-resolved constant, the return type of the bootstrapmethod must be convertible to the type of the constant, asrepresented by its field type descriptor. For example, if thedynamic constant has a field type descriptor of"C"(char) then the bootstrap method return type could beObject,Character, orchar, but notint orInteger.

Since:
1.7
  • Related Packages
    Package
    Description
    Provides classes that are fundamental to the design of the Javaprogramming language.
  • Class
    Description
    ACallSite is a holder for a variableMethodHandle, which is called itstarget.
    Bootstrap methods for dynamically-computed constants.
    AConstantCallSite is aCallSite whose target is permanent, and can never be changed.
    LambdaConversionException
    Methods to facilitate the creation of simple "function objects" thatimplement one or more interfaces by delegation to a providedMethodHandle,possibly after type adaptation and partial evaluation of arguments.
    A method handle is a typed, directly executable reference to an underlying method, constructor, field, or similar low-level operation, with optional transformations of arguments or return values.
    A symbolic reference obtained by cracking a direct method handleinto its constituent symbolic parts.
    This class consists exclusively of static methods that help adaptmethod handles to other JVM types, such as interfaces.
    This class consists exclusively of static methods that operate on or returnmethod handles.
    Alookup object is a factory for creating method handles,when the creation requires access checking.
    The set of class options that specify whether a hidden class created byLookup::defineHiddenClass method is dynamically added as a new memberto the nest of a lookup class and/or whether a hidden class hasa strong relationship with the class loader marked as its defining loader.
    A method type represents the arguments and return type accepted andreturned by a method handle, or the arguments and return type passedand expected by a method handle caller.
    AMutableCallSite is aCallSite whose target variable behaves like an ordinary field.
    Serialized form of a lambda expression.
    StringConcatException is thrown byStringConcatFactory when linkageinvariants are violated.
    Methods to facilitate the creation of String concatenation methods, thatcan be used to efficiently concatenate a known number of arguments of knowntypes, possibly after type adaptation and partial evaluation of arguments.
    ASwitchPoint is an object which can publish state transitions to other threads.
    An entity that has a type descriptor.
    An entity that has a field type descriptor.
    An entity that has a method type descriptorMethod descriptors conforming to JVMS4.3.3 can be describednominally viaMethodType::describeConstable;otherwise they cannot be described nominally.
    A VarHandle is a dynamically strongly typed reference to a variable, or to aparametrically-defined family of variables, including static fields,non-static fields, array elements, or components of an off-heap datastructure.
    The set of access modes that specify how a variable, referenced by aVarHandle, is accessed.
    AVolatileCallSite is aCallSite whose target acts like a volatile variable.
    Thrown to indicate that code has attempted to call a method handlevia the wrong method type.