To support dynamic types and method dispatch, my programming language introduces a type called dynamic
. When calling a method on a callee whose type is dy
The point of invokedynamic
is not that the JVM is going to implement a dynamic type system. That would be a drastic change that affects lots of parts of the JVM and may cause performance degradation even at places not using that feature, for very little benefit: after all, every dynamic language has a different idea of a type system.
Instead, invokedynamic
allows you to implement your dynamic type system. You can do exactly the things, a JVM and hotspot optimizer do, but using your own semantics. So you are implementing a dynamic method invocation dispatcher like you would do without invokedynamic
. On the first invocation you will link to that dynamic dispatcher which will use the runtime types of the arguments to find the target. But it may also record the targets and if it finds out that a particular call site has monomorphic behavior, its target may get redirected to an optimized dispatcher or even directly to the target method, depending on how you protect against later-on changes of the behavior. E.g., if the runtime will detect the invalidation of the related invariants, e.g. by loading a new type into the runtime, you may link the call site directly to the target and change the target (again) when the event invalidating the target happens. Or you direct the invocation to a sentinel code which checks the preconditions for the optimized call before executing it, assuming that the check for a known precondition is faster than the full dynamic lookup.
As said, that’s similar to the optimization techniques, the JVM uses itself for invocations bearing Java semantics. But you have the control over the existing kinds of invocations and how to resolve them. Of course, you can implement all that without the invokedynamic
instruction, using ordinary object structures modelling your type system, however, the invokedynamic
instruction allows you to tell the JVM the semantic of caller and callee which can then be used by the HotSpot optimizer to make a direct link between them.
The "dynamic" part of invokedynamic
does not mean that a method arguments can have dynamic types. It rather means that the behavior of invoke
instruction can be customized. The exact types of invokedynamic
arguments are known at compile time.