Module java.base

Package java.lang.invoke

The java.lang.invoke package contains dynamic language support provided directly byprovides low-level primitives for interacting with the Java core class libraries and virtual machineVirtual Machine.

As described in the Java Virtual Machine Specification, certain types in this package haveare given special relations to dynamic language support intreatment by the virtual machine:

  • The classes MethodHandleVarHandle contain signature polymorphic methods which can be linked regardless of their type descriptor. Normally, method linkage requires exact matching of type descriptors.
  • The JVM bytecode format supports immediate constants of the classes MethodHandle and MethodType.
  • SummaryThe invokedynamic instruction makes use of bootstrap MethodHandle constants to dynamically resolve CallSite objects for custom method invocation behavior.
  • The ldc instruction makes use of bootstrap MethodHandle constants to dynamically resolve custom constant values.

Dynamic resolution of relevant Java Virtual Machine changescall sites and constants

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

Each occurrence of an Dynamically-computed call sites

An invokedynamic instruction is called a dynamic call site .

invokedynamic instructions

A dynamic call site isoriginally in an unlinked state. In this state, there is no target method for the call siteinstruction to invoke.

Before the JVM can execute a dynamic call site (an invokedynamic instruction), the call siteinstruction must first be linked. Linking is accomplished by calling a bootstrap method which is given the static information content of the call site, and which must produce a method handle CallSite that gives the behavior of the call siteinvocation.

Each invokedynamic instruction statically specifies its own bootstrap method as a constant pool reference. The constant pool reference also specifies the call siteinvocation's name and method type descriptor, just like invokevirtualinvokestatic and the other invoke instructions. Linking starts

Dynamically-computed constants

The constant pool may contain constants tagged CONSTANT_Dynamic, equipped with resolvingbootstrap methods which perform their resolution. Such a dynamic constant is originally in an unresolved state. Before the JVM can use a dynamically-computed constant, it must first be resolved. Dynamically-computed constant pool entry for theresolution is accomplished by calling a bootstrap method which is given the static information content of the constant, and resolvingwhich must produce a value of the constant's statically declared type.

Each dynamically-computed constant statically specifies its own bootstrap method as a MethodType object forconstant pool reference. The constant pool reference also specifies the constant's name and field type descriptor of, just like getstatic and the dynamicother field reference instructions. (Roughly speaking, a dynamically-computed constant is to a dynamically-computed call site . This resolution process may trigger class loading. It may therefore throw an error ifas a class failsCONSTANT_Fieldref is to load. This error becomesa CONSTANT_Methodref.)

Execution of bootstrap methods

Resolving a dynamically-computed call site or constant starts with resolving constants from the constant pool for the following items:
  • the bootstrap method, a CONSTANT_MethodHandle
  • the abnormal terminationClass or MethodType derived from type component of the dynamic call site execution. Linkage does not trigger class initialization.CONSTANT_NameAndType descriptor
  • static arguments, if any (note that static arguments can themselves be dynamically-computed constants)

The bootstrap method is then invoked on at least three values, as if by MethodHandle.invoke, with the following arguments:

  • a MethodHandles.Lookup, which is a lookup object on the caller class in which dynamicdynamically-computed constant or call site occurs
  • a String, the methodname mentioned in the call siteCONSTANT_NameAndType
  • a MethodType or Class, the resolved type descriptor of the CONSTANT_NameAndType
  • a Class, the calloptionally, any numberresolved type descriptor of additional static arguments taken fromthe constant pool In all cases, bootstrap method invocation is as, if by MethodHandle.invokeWithArguments, (Thisit is also equivalent to generic invocation ifa dynamic constant
  • the number ofadditional resolved static arguments is small enough.), if any

For an invokedynamic instructiona dynamically-computed call site, the returned result must be convertible toa non-null reference to a CallSite. If the returned result cannot be converted to the expected type, BootstrapMethodError is thrown. The type of the call site's target must be exactly equal to the type derived from the dynamic call siteinvocation's type descriptor and passed to the bootstrap method, otherwise. If these conditions are not met, a BootstrapMethodError is thrown. On success the call site then becomes permanently linked to the invokedynamic instruction.

For a dynamically-computed constant, the first parameter of the bootstrap method must be assignable to MethodHandles.Lookup. If this condition is not met, a BootstrapMethodError is thrown. On success the result of the bootstrap method is cached as the dynamic call siteresolved constant value.

If an exception, E say, occurs when linkingduring execution of the call sitebootstrap method, then the linkageresolution fails and terminates abnormally. E is rethrown if the type of E is Error or a subclass, otherwise a BootstrapMethodError that wraps E is thrown. If this happens, the same Error or subclasserror will thebe thrown for all subsequent attempts to execute the invokedynamic instruction or load the dynamic call site.timingdynamically-computed constant.

Timing of linkage A dynamic call siteresolution

An invokedynamic 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 within a thread that is attempting a first execution or first use.

If there are several such threads, the bootstrap method may be invoked in several threads concurrently. Therefore, bootstrap methods which access global application data must take the usual precautions against race conditions. In any case, every invokedynamic instruction is either unlinked or linked to a unique CallSite object.

In an application which requires dynamic call sitesinvokedynamic instructions with individually mutable behaviors, their bootstrap methods should produce distinct CallSite objects, one for each linkage request. Alternatively, an application can link a single CallSite object to several invokedynamic instructions, in which case a change to the target method will become visible at each of the instructions.

If several threads simultaneously execute a bootstrap method for a single dynamicdynamically-computed call site or constant, the JVM must choose one CallSite objectbootstrap method result and install it visibly to all threads. Any other bootstrap method calls are allowed to complete, but their results are ignored, and their dynamic call site invocations proceed with the originally chosen target object.

Discussion: These rules do not enable the JVM to duplicate dynamicshare call sites, or to issue “causeless” bootstrap method calls. Every dynamic call siteinvokedynamic 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.

typesTypes of bootstrap methods

As long as eachFor a dynamically-computed call site, the bootstrap method is invoked with parameter types MethodHandles.Lookup, String, MethodType, and the types of any static arguments; the return type is CallSite.

For a dynamically-computed constant, the bootstrap method can be correctlyis invoked with parameter types MethodHandles.Lookup, String, Class, and the types of any static arguments; the return type is the type represented by the Class.

Because MethodHandle.invoke, its detailed allows for adaptations between the invoked method type and the bootstrap method handle's method type, there is arbitraryflexibility in the declaration of the bootstrap method. For a dynamically-computed constant the first parameter type of the bootstrap method handle must be assignable to MethodHandles.Lookup, other than that constraint the same degree of flexibility applies to bootstrap methods of dynamically-computed call sites and dynamically-computed constants. Note: this constraint allows for the future possibility where the bootstrap method is invoked with just the parameter types of static arguments, thereby supporting a wider range of methods compatible with the static arguments (such as methods that don't declare or require the lookup, name, and type meta-data parameters).

For example, for dynamically-computed call site, a the first argument could be Object instead of MethodHandles.Lookup, and the return type could also be Object instead of CallSite. (Note that the types and number of the stacked arguments limit the legal kinds of bootstrap methods to appropriately typed static methods and constructors of CallSite subclasses.)

If a given invokedynamic instruction specifies no static arguments, the instruction's bootstrap method will be invoked on three arguments, conveying the instruction's caller class, name, and method type.If the invokedynamic instruction specifies one or more static arguments, those values will be passed as additional arguments to the method handle. (Note that because there isa limit of 255 arguments to any method, at most 251 extra arguments can be supplied to a non-varargs bootstrap method, since the bootstrap method handle itself and its first three arguments must also be stacked.) The bootstrap method will be invoked as if by MethodHandle.invokeWithArguments. A variable-arity bootstrap method can accept thousands of static arguments, subject only by limits imposed by the class-file format. The normal argument conversion rules for MethodHandle.invoke apply to all stacked arguments. For example, if apushed 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 bit 0x0080 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 interaction between CONSTANT_MethodHandle constants, the modifier bit for variable arity methods, and the asVarargsCollector transformation.)

Given these rules, here are examples of legal bootstrap method declarations for dynamically-computed call sites, given various numbers N 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 type String and Integer (or int), respectively. The second-to-last example assumes that all extra arguments are of type String. The other examples work with all types of extra arguments. As noted above,Note that all the actual method type ofexamples except the bootstrap method can vary. For example, the fourth argument could be MethodHandle,second and third also work with dynamically-computed constants if that isthe return type ofis changed to be compatible with the correspondingconstant in the CONSTANT_InvokeDynamic entry. In that case, the MethodHandle.invoke call will pass the extra method handle constant's declared type (such as anObject , but the type matching machinery of MethodHandle.invoke will cast the reference backwhich is always compatible).

Since dynamically-computed constants can be provided as static arguments to MethodHandle before invokingbootstrap methods, there are no limitations on the bootstrap method. (If a string constant were passed instead, by badly generated code, that cast would then fail, resulting in a BootstrapMethodError.) Note that, as a consequencetypes of the above rules, thebootstrap method may accept a primitive argument, if it can be represented by a constant pool entryarguments. However, arguments of type boolean, byte, short, or char cannot be created for bootstrap methods, since such constants cannot bedirectly represented in thesupplied by CONSTANT_Integer constant pool , andentries, since the invocation of the bootstrap method willasType conversions do not perform the necessary narrowing primitive conversions.

ExtraIn the above examples, the return type is always CallSite, but that is not a necessary feature of bootstrap method arguments are intended to allow language implementors to safely and compactly encode metadatamethods. In principle,the name and extra arguments are redundant, since eachcase of a dynamically-computed call site could, the only requirement is that the return type of the bootstrap method must be given its own uniqueconvertible (using the asType conversions) to CallSite, which means the bootstrap method . Suchreturn type might be Object or ConstantCallSite. In the case of a practice woulddynamically-resolved constant, the return type of the bootstrap method must be likelyconvertible to produce large class files andthe type of the constant, as represented by its field type descriptor. For example, if the dynamic constant poolshas a field type descriptor of "C" (char) then the bootstrap method return type could be Object, Character, or char, but not int or Integer.

Since:
1.7