InvokeDynamic Updates in OpenJDK
Just before Christmas the OpenJDK builds started to include an updated version of the JSR 292 API, which, whilst not yet final, gives a good indication as to how the JSR is shaping up. For those not familiar with it, JSR 292 adds a new bytecode instruction, invokedynamic, that supports the execution of method invocations in the absence of static type information, as InfoQ previously explored.
John Rose’s blog contains a summary of the major changes. Amongst them:
- The class CallSite is now abstract, split into three subclasses: MutableCallSite, ConstantCallSite, and VolatileCallSite.
- The class java.dyn.Linkage is deprecated and will be removed in the Public Final Draft.
- The class java.dyn.JavaMethodHandle has been removed. From Rose’s blog: “Use Lookup.findVirtual (cached in a private static final) and MethodHandle.bindTo to convert a random object to a method handle. Use MethodHandles.asInstance to convert a method handle to a random SAM interface.”
Some areas of the API are still provisional and could yet change, including the MethodHandles.AsInstanceObject interface, which provides a mechanism for applications to repeatedly convert between method handles and SAM objects, without the risk of creating unbounded delegation chains. In addition the JVM options which currently have to be enabled to work with JSR 292 (XX:+UnlockExperimentalVMOptions, -XX:+EnableInvokeDynamic, and -XX:+EnableMethodHandles) will be turned on by default in the near future,
Disappointingly JDK 7 will not now include syntax support in the Java language for issuing invokedynamic instructions. These may be re-introduced as part of Project Lambda in the JDK 8 timeframe (the actual plan to implement Java lambda uses several features introduced by JSR 292 including Method Handles and dynamic invocation). In the meantime however, Rose has put together a small classfile transformer, named “indify” which can be used to generate invokedynamic instructions, and can also generate “ldc” instructions for MethodHandle and MethodType constants. Rémi Forax has also looked at the problem, developing a small class called DynamicIndy. As Forax explains, the class uses the Java bytecode manipulation library ASM 4.0 (not yet released) to generate a static method that calls invokedynamic. The static method is then converted to a MethodHandle that can be called in Java.
Whilst JSR 292 focuses primarily on the needs of dynamic languages it has become apparent that Java itself is now a candidate user of the API, as noted above. In view of this it has been suggested that the java.dyn package be renamed. Brian Goetz and Mark Reinhold propose to rename it to java.lang.mh (mh stands for MethodHandle), however other suggestions are welcome and can be made in the first instance at Rémi Forax’s blog.
Caitie McCaffrey Apr 24, 2015