0

I noticed new objects are not being created in case of lambdas unlike anonymous classes. Could someone help me understand this please?

    //case 1: anonymous class
    for (int i = 0; i < 3; i++) {
        Runnable r = new Runnable() { @Override public void run() { System.out.println("blah");}};
        System.out.println("Anonymous: " + r.hashCode());
    }

    //case 2: lambdas
    for (int i = 0; i < 3; i++) {
        Runnable r = () -> System.out.println("blah");
        System.out.println("Lambda: " + r.hashCode());
    }

Prints

Lambda: 1915503092
Lambda: 1915503092
Lambda: 1915503092
Anonymous: 1535128843
Anonymous: 1567581361
Anonymous: 849460928
4
  • Why in your opinion should they return new objects? Commented Oct 28, 2015 at 12:28
  • @the8472, I am new to Lambdas and was under the impression that it was a just a syntactic sugar over anonymous classes. Hence I was expecting that it should create new objects. Apparently, JVM is smart enough to not create multiple objects for stateless lambdas. Commented Oct 28, 2015 at 12:36
  • They mostly code like anonymous inner classes, but that does not mean that they simply are syntactic sugar. You should avoid making that assumption the future, there are other subtle differences too. Commented Oct 28, 2015 at 12:43
  • I learned that now. Thanks @the8472. Commented Oct 28, 2015 at 12:48

1 Answer 1

2

The exact behaviour of the JVM when optimizing lambdas is not specified. The HotSpot JVM optimizes stateless lambdas by creating a singleton for them.

See this answer to "Does a lambda expression create an object on the heap every time it's executed?" for details: https://stackoverflow.com/a/27524543/281469

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Brian Goetz's comment in the link provided answered the question.
@bcoughlan If this question is a duplicate of another question, you should be voting to close it as a duplicate, not posting a link to the original as an answer.
The correct statement should be, the current implementation of HotSpot JVM creates singletons for stateless lambdas. Future versions might even fold different, equivalent lambda expressions into one instance or even reuse stateful lambdas (when their captured values are identical). We might even see future versions not creating singletons, if there are value type optimizations in that future JVM promising more benefit…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.