2

Lets assume that we have the following code:

Thread t = new Thread(new Runnable(){
    public void run(){
        System.out.println("separated thread");
    }
});
t.start();

The replaceable of the above in Java 8 is:

Thread t = new Thread(() -> System.out.println("separated thread"));
t.start();

Now as far as I know lambda expression in other languages that runs on the JVM for example Scala and Groovy, is simply treated as an anonymous block of code where the compiler replaces the expression with its equivalent anonymous inner class resulting a new class for each call, i know for a fact that the above is not good at all in term of size and runtime.

Is this the case in Java? if not how does it deal with lambda (in details)? I would also appreciate; if the mechanism behind using invokedDynamic feature to supports lambda is explained?

Ahmad Sanie
  • 3,678
  • 2
  • 21
  • 56
  • AFAIK lambdas are just another way of writing anonymous classes, i.e. the compiler should transform them. Thus both variants should basically equal from a runtime point of view. – Thomas Nov 08 '16 at 09:36
  • @Thomas Apparently (http://stackoverflow.com/questions/16827262/how-will-java-lambda-functions-be-compiled?noredirect=1&lq=1) the compiler does not do this transformation, but leaves it up to the runtime how exactly it wants to generate code for the lambda on the fly. – Thilo Nov 08 '16 at 09:38
  • And I believe the latest Scala version (it requires Java8) also makes use of this more-performant mechanism. – Thilo Nov 08 '16 at 09:41
  • @Thilo I couldn't find any satisfying answer in both of the possible duplicates, I'm curious about the mechanism behind using invokedDynamic feature to supports lambda and deals with it differently – Ahmad Sanie Nov 08 '16 at 09:41
  • 1
    @AhmadAlsanie How about this one: http://stackoverflow.com/a/26257532/14955 – Thilo Nov 08 '16 at 09:43
  • @Thilo yup that's the one, Thank you very much :) – Ahmad Sanie Nov 08 '16 at 09:46

0 Answers0