Social Media

How Lambda’s And Anonymous Inner Classes(AIC) Work

At first glance a lambda looks like a short hand version of an anonymous inner class. But they are not. This post covers the differences between lambda’s and AIC’s

Key Points

  • Lambdas implement a functional interface
  • Anonymous Inner Classes can extend a class or implement an interface with any number of methods
  • Variables – Lambda’s can only access final or effectively final
  • State – Anonymous inner classes can use instance variables so can have state, lambda’s cannot
  • Scope – Lambda part of its enclosing scope – so cant define a variable with same name as variable in enclosing scope
  • Compilation – Anonymous compiles to a class, while lambda is an invokedynamic instruction

How they work

Anonymous Inner Classes(AIC’s)

  • Compiler generates a class file for each anonymous inner class
  • For example – AnonymousInnerClass$1.class
  • Like all classes it needs to be loaded and verified at startup

Lambda

The key to the lambda implementation is the InvokeDynamic instruction introduced in Java 7. This allows dynamic languages to bind to symbol at runtime.

A lambda works like this –

  • Generates invokedynamic call site, and uses a lambdafactory to return the functional implementation
  • lambda convered to a method to be invoked by invokedynamic
  • Method stored in class as private static method
  • Two lambda types – non-capturing – only uses fields inside its body
    – capturing  – accesses fields outside its body

Non-capturing Lambda

Doesnt access fields outside its body

If we decode the class file using the cfr decompiler, we see the –

  • LambdaMetafactory
  • Lambda is a static void method in our class

Capturing Lambda

Accesses final or effectively final fields outside its body –

This decompiles to –

The interesting part is the lambda$0 method signature has gone from empty to taking a parameter String

References

https://www.infoq.com/articles/Java-8-Lambdas-A-Peek-Under-the-Hood

http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html
 

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About

follow me on:

Leave a Comment:

1 comment
Java Annotated Monthly – March 2017 | IntelliJ IDEA Blog says 03/03/2017

[…] How Lambdas And Anonymous Inner Classes Work […]

Reply
Add Your Reply