The release of Java 7 contained several new features that seemed, at first sight, to be of limited use to Java developers, and we covered some of those in our article.

However, one feature in particular proved to be crucial in implementing the "headline" features of Java 8 (such as lambdas and default methods). In this article, we want to dive deeper on invokedynamic and explain why it is such a powerful tool for the Java platform, and for JVM languages such as JRuby and Nashorn.

The earliest work on invokedynamic goes back to at least 2007 with the first successful dynamic invocation taking place on August 26 2008. This predates Sun’s acquisition by Oracle and shows that this feature has been in progress for a long time, by the standards of most developers.

invokedynamic is remarkable in that it was the first new bytecode ever since Java 1.0. It joined the existing invoke bytecodes invokevirtual, invokestatic, invokeinterface and invokespecial. These four existing opcodes implement all forms of method dispatch that Java developers are typically familiar with, specifically:

invokevirtual - the standard dispatch for instance methods

invokestatic - used to dispatch static methods

invokeinterface - used to dispatch a method call via an interface

invokespecial - used when non-virtual (i.e. "exact") dispatch is required

Some developers may be curious as to why the platform requires all four opcodes, so let’s look at a simple example that uses the different invoke opcodes, to demonstrate the difference between them:

This showcases three of the four invoke opcodes (and the remaining one, invokestatic is a fairly trivial extension). To start with, we can see that the two calls (at bytes 11 and 28 in the run method):

ls.add("Good Day")

and

als.add("Dydh Da")

look very similar in Java source code but are actually represented differently in bytecode.

To javac, the variable ls has the static type of List<String>, and List is an interface. So the precise location in the runtime method table (usually called a "vtable") of the add() method has not yet been determined at compile time. The source code compiler therefore emits an invokeinterface instruction, and defers the actual lookup of the method until runtime, when the real vtable of ls can be inspected, and the location of the add() method found.

By contrast, the call als.add("Dydh Da") is received by als, and the static type of this is a class type - ArrayList<String>. This means that the location of the method in the vtable is known at compile time. javac is therefore able to emit an invokevirtual instruction for the exact vtable entry. The final choice of method while still be determined at runtime, because this allows for the possibility of method overriding, but the vtable slot has been determined at compile time.

Not only that, but the example also shows two of the possible use cases of invokespecial. This opcode is used in those cases where dispatch should be exactly determined at runtime, and in particular, method overriding is neither desired nor possible. The two cases the example demonstrates are private methods and super calls, because such methods are known at compile time and cannot be overridden.

The astute reader will have noticed that all calls to Java methods are compiled to one of these four opcodes so the question arises - what is invokedynamic for, and why is it useful to Java developers?

The features main goal was to create a bytecode to handle a new type of method dispatch - that essentially allows application-level code to determine which method a call will execute, and to do so only when the call is about to execute. This allows language and framework writers to support much more dynamic programming styles than the Java platform previously provided.

The intent is that user code determines dispatch at runtime using the method handles API whilst not suffering the performance penalties and security problems associated with reflection. In fact, the stated aim of invokedynamic is to be as fast as regular method dispatch (invokevirtual) once the feature has matured sufficiently.

When Java 7 arrived, the JVM had support for executing the new bytecode, but regardless of the Java code submitted, javac would never produce bytecode that included invokedynamic. Instead, the feature was used to support JRuby and other dynamic languages running on the JVM.

This changed in Java 8, where invokedynamic is now generated and used under the hood to implement lambda expressions and default methods, as well as the primary dispatch mechanism for Nashorn. However, there is still no direct way for Java application developers to do fully dynamic method resolution. That is, the Java language does not have a keyword or library that will create general-purpose invokedynamic call sites. This means that the mechanism remains obscure to most Java developers, despite the power it provides. Let’s see how we can leverage that in our code.

Introduction to Method Handles

For invokedynamic to work correctly, a key concept is the method handle. This is a way to represent the method that should be called from the invokedynamic call site. The general idea is that each invokedynamic instruction is associated with a special method (known as a bootstrap method or BSM). When the invokedynamic instruction is reached by the interpreter, the BSM is called. It returns an object (containing a method handle) that indicates which method the call site should actually execute.

This is somewhat similar to reflection, but reflection has limitations that made it unsuitable for use with invokedynamic. Instead, the java.lang.invoke.MethodHandle (and subclasses) were added to the Java 7 API, to represent methods that invokedynamic can target. The class MethodHandle receives some special treatment from the JVM, in order to operate correctly.

One way to think of method handles is as core reflection done in a safe, modern way with maximum possible type safety. They are needed for invokedynamic but can also be used standalone.

Method Types

A Java method can be considered to be made up of four basic pieces:

Name

Signature (including return type)

Class where it is defined

Bytecode that implements the method

This means that if we want to refer to methods we need a way of representing method signatures efficiently (rather than using the horrible Class<?>[] hacks that reflection is forced to use).

To put it another way, one of the first building blocks needed for method handles is a way of representing method signatures for lookup. In the Method Handles API, introduced in Java 7, this role is fulfilled by the java.lang.invoke.MethodType class, which uses immutable instances to represent signatures. To obtain a MethodType, use the methodType() factory method. This is a variadic method that takes class objects as arguments.

The first argument is the class object corresponding to the signature’s return type; the remaining arguments are the class objects that correspond to the types of the method arguments in the signature. For example:

Using the MethodType we can now use it, along with the name and the class that defines the method to lookup the method handle. To do this, we need to call the static MethodHandles.lookup() method. This gives us a "lookup context" that is based on the access rights of the currently executing method (i.e. the method that called lookup()).

The lookup context object has a number of methods that have names that start with "find", e.g. findVirtual(), findConstructor(), findStatic(). These methods will return the actual method handle, but only if the lookup context was created in a method that could access (call) the requested method. Unlike reflection, there is no way to subvert this access control. In other words, method handles have no equivalent of the setAccessible() method. For example:

The difference between the two is that invokeExact() tries to call the method handle directly with the precise arguments provided. On the other hand, invoke() has the ability to slightly alter the method arguments if needed. invoke() performs an asType() conversion which can convert arguments according to this set of rules:

Primitives will be boxed if required

Boxed primitives will be unboxed if required

Primitives will be widened if necessary

A void return type will be converted to 0 (for primitive return types) or null for return types that expect a reference type

null values are assumed to be correct and passed through regardless of static type

Let’s look at a simple invocation example that takes into account these rules:

In more complex examples, method handles can provide a much clearer way to perform the same dynamic programming tasks as core reflection. Not only that, but method handles have been designed from the start to work better with the low-level execution model of the JVM and potentially can provide much better performance (although the performance story is still unfolding).

Method Handles and invokedynamic

The invokedynamic uses method handles via the bootstrap methods mechanism. Unlike invokevirtual, invokedynamic instructions have no receiver object. Instead, they act like invokestatic, and use a BSM to return an object of type CallSite. This object contains a method handle (called the "target") that represents the method that is to be executed as the result of the invokedynamic instruction.

When a class containing invokedynamic is loaded, the call sites are said to be in an "unlaced" state, and after the BSM returns, the resulting CallSite and method handle is said to be "laced" into the call site.

The signature for a BSM looks like this (note that the BSM can have any name):

If we want to create code that actually contains invokedynamic, we will need to use a bytecode manipulation library (as the Java language doesn’t contain the constructs we need). In the rest of this article, we will need to use the ASM library to generate bytecode that includes invokedynamic instructions. From the point of view of Java applications, these appear as regular class files (although they, of course, have no possible Java source code representation). They are treated by Java code as "black boxes", that we can nonetheless call methods on and make use of invokedynamic and related functionality.

Let’s look at an ASM-based class for creating a "Hello World" using invokedynamic.

The code is divided into two sections, the first of which uses the ASM Visitor API to create a class file called kathik.Dynamic. Note the key call to visitInvokeDynamicInsn(). The second section contains the target method that will be laced into the call site, and the BSM that the invokedynamic instruction needs.

Note that these methods are within the InvokeDynamicCreator class and not part of our generated class kathik.Dynamic. This means that at runtime InvokeDynamicCreator must also be on the classpath as well as kathik.Dynamic, or the method won’t be able to be found.

When InvokeDynamicCreator is run, it creates a new class file, Dynamic.class, which contains an invokedynamic instruction, as we can see by using javap on the class:

This example has shown the simplest case of invokedynamic, which uses the special case of a constant CallSite object. This means that the BSM (and lookup) is done only once and so subsequent calls are fast.

However, more sophisticated usages of invokedynamic can get complex quickly, especially when the call site and target method can change during the lifetime of the program.

In the next article, we will examine some more advanced use cases and build some examples, as well as dig deeper into the details of invokedynamic.

About the Author

Ben Evans is the CEO of jClarity, a Java/JVM performance analysis startup. In his spare time he is one of the leaders of the London Java Community and holds a seat on the Java Community Process Executive Committee. His previous projects include performance testing the Google IPO, financial trading systems, writing award-winning websites for some of the biggest films of the 90s, and others.

Is your profile up-to-date? Please take a moment to review and update.

Email Address

Note: If updating/changing your email, a validation request will be sent

Company name:

Keep current company name

Update Company name to:

Company role:

Keep current company role

Update company role to:

Company size:

Keep current company Size

Update company size to:

Country/Zone:

Keep current country/zone

Update country/zone to:

State/Province/Region:

Keep current state/province/region

Update state/province/region to:

Subscribe to our newsletter?

Subscribe to our architect newsletter?

Subscribe to our industry email notices?

You will be sent an email to validate the new email address. This pop-up will close itself in a few moments.

We notice you're using an ad blocker

We understand why you use ad blockers. However to keep InfoQ free we need your support. InfoQ will not provide your data to third parties without individual opt-in consent. We only work with advertisers relevant to our readers. Please consider whitelisting us.