Invoke Dynamic

Preview:

Citation preview

InvokeDynamicJava 7 dynamically typed language support

arkadi.shishlov@gmail.com

Statically typed languages

Java

Scala

C#

C

C++

F#

Haskel

Dynamic languages

Groovy

Clojure

JavaScript

Perl

Python

Ruby

PHP

Dynamic language

object runtime alteration (open program code)

metaobject protocol

eval

functional programming, closures, macros

Dynamically typed language

type checking performed at runtime

variable does not have a type

value is associated with a type

duck typing

The program must be compiled to bytecode to achieve Java level performance

Use case

groovy:000> f = { it + it }===> groovysh_evaluate$_run_closure1@dc737begroovy:000> f(1) ===> 2groovy:000> f("qw")===> qwqwgroovy:000> [2, "qwe"].collect(f)===> [4, qweqwe]groovy:000>

collect (list, func) { foreach (list) push (result, func (it))}

The probleminvokevirtual

some/class/Name.func(Ljava/lang/String)Z,

objectref,

arg1, arg2, ...

invokespecial

invokestatic has similar calling convention

invokeinterface

The solution

Reflection is (relatively) slow

There are others possibilities

Java 7 approach - JSR292

invokedynamic (indy)

boostrapFuncRef,

NameLiteral(Lorg/jruby/runtime/builtin/IRubyObject)

Lorg/jruby/runtime/builtin/IRubyObject,

arg1, arg2, ...

java.lang.invoke.*

MethodHandle

CallSite

ConstantCallSite

MutableCallSite

VolatileCallSite

MethodType

public static CallSite bootstrap ( MethodHandles.Lookup lookup, String dynMethodName, MethodType dynMethodType) throws Throwable {

MethodHandle handle = lookup.findStatic( SomeClosure.class, "func", MethodType.methodType( Integer.class, Object.class, Object.class)); if (!dynMethodType.equals(handle.type())) handle = handle.asType(dynMethodType);

return new ConstantCallSite(handle);}

MutableCallSite.setTarget(MethodHandle newTarget)

Advantages

fast

JIT-ted

inlined

signature polymorphism, arguments adaptation

Work in ProgressJRuby - works, sort of; Mirah

Rhino (JavaScript) - J.Rose experiment, V8 for performance freaks

Groovy - proposed for 1.9, no impl

Jython (Python) - different priorities: PyPy, Cython, language features upgrade

Clojure - many features not applicable to Indy

PHP.reboot

Learn more

http://download.java.net/jdk7/docs/technotes/guides/vm/multiple-language-support.html

JDK 7 JSR-292 java.lang.invoke.* API

JRuby source: src/org/jruby/compiler/impl/*.java

http://code.google.com/p/jsr292-cookbook/

http://mail.openjdk.java.net/pipermail/mlvm-dev/

http://www.oracle.com/technetwork/issue-archive/2010/10-may/o30java-099612.html

http://blog.headius.com/2008/09/first-taste-of-invokedynamic.html

Recommended