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
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
MFIhsan
  • 1,037
  • 3
  • 15
  • 35
  • Why in your opinion *should* they return new objects? – the8472 Oct 28 '15 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. – MFIhsan Oct 28 '15 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. – the8472 Oct 28 '15 at 12:43
  • I learned that now. Thanks @the8472. – MFIhsan Oct 28 '15 at 12:48

1 Answers1

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

Community
  • 1
  • 1
bcoughlan
  • 25,987
  • 18
  • 90
  • 141
  • Thanks. Brian Goetz's comment in the link provided answered the question. – MFIhsan Oct 28 '15 at 12:34
  • @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. – cimmanon Oct 28 '15 at 12:48
  • 2
    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… – Holger Oct 28 '15 at 13:16