Use invokedynamic to implement multiple dispatch

£可爱£侵袭症+ 提交于 2019-12-04 09:31:02

问题


I wondered if Java7's new invokedynamic bytecode instruction could be used to implement multiple dispatch for the Java language. Would the new API under java.lang.invoke be helpful to perform such a thing?

The scenario I was thinking about looked as follows. (This looks like an application case for the visitor design pattern, but there may be reasons that this is not a viable option.)

class A {} 
class A1 extends A {}
class A2 extends A {}

class SomeHandler {
    private void doHandle(A1 a1) { ... }
    private void doHandle(A2 a2) { ... }
    private void doHandle(A a) { ... }

    public void handle(A a) {
        MultipleDispatch.call(this, "doHandle", a);
    }
}

The library class MultipleDispatch would then do something of the kind:

class MultipleDispatch {

    public static Object call(Object receiver, String method, Object...arg) {
        // something like that in byte code
        #invokeDynamic "doHandle" "someBootstrap"
    }

    static CallSite someBootstrap {
        // resolve that dynamic method call.
    }
}

(I am aware of MultiJava, but can this be achieved in a Java-pure fashion?)


回答1:


Since I have no experience with invokedynamic, I do not know how good the performance and type-safety would be, but can only give some pointers:

  • the Da Vinci Machine Project offers multiple dispatch via invokedynamic (see Multiple Dispatch/src/invokedynamicmultipledispatch/);
  • Charles Oliver Natter has talked about applications of invokedynamic on JAX2012. The slides do not go into details at all, but I think I came across more details in a video or podcast talking about JAX2012, which I cannot find right now.
  • Christopher Dutchyn's JVM Multiple Dispatch is an alternative approach without invokedynamic. His COOTS '01 Paper and these slides have a lot of performance information/benchmarking (and are a good read after you've finished your disseration ;)



回答2:


The instruction invokedynamic is purely a JVM instruction, it does not relate to dynamic dispatch. The dispatch is completed by method handles (method handle graph and method handle tree are also OK.) that comprises multiple method handle instances. A path in the graph (tree) represents one dispatch path.

For your given sample, i would possible construct a graph (Different people might have different graph result ). IN this graph, the traverse of method handles in the graph is the way how disptach completes.



来源:https://stackoverflow.com/questions/11014917/use-invokedynamic-to-implement-multiple-dispatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!