everett1992
everett1992

Reputation: 2661

Java double brace initialization vs lambda

If you search 'java double brace' you'll find strong arguments against using it.

Every time someone uses double brace initialisation, a kitten gets killed. https://stackoverflow.com/a/27521360/555631

The arguments are you're creating way too many anonymous classes and you're potentially creating a memory leak.

Are lambdas any different? They each create an anonymous inner class, they each reference their enclosing closure.

Upvotes: 2

Views: 447

Answers (2)

rgettman
rgettman

Reputation: 178263

Lambda expressions are different from an anonymous inner class that happens to implement a functional interface.

Anonymous inner classes will create their own class file at compilation, usually something along the lines of Foo$1.class, if it's contained in the Foo class. It is a fully functional class that implements an interface or subclasses a class. To reference local values outside its scope, it will, behind the scenes, create an instance variable in the anonymous inner class that represents a copy of the value. This is why the variable must be effectively final -- otherwise the actual variable may change and the copy may be stale.

Lambda expressions don't create anonymous inner classes. They use a java.lang.invoke.LambdaMetafactory that produces a CallSite that can be used later to execute the lambda expression. The lambda expression, whether it's a block or an expression, gets converted to a hidden private static method within the class in which it's contained. Instead of creating a class with a hidden variable, captured values get translated into parameters of the hidden private static method. Local values still must be effectively final because the value passed to the method is again a copy. The method gets invoked by a invokedynamic instruction in the JVM.

Sources:

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198033

Yes, they are different.

  • Lambdas don't actually necessarily create anonymous classes -- they're certainly not just translated into the equivalent anonymous class. Their creation is much more convoluted than that, and often ends up with an anonymous class created at runtime, but not necessarily.
  • Lambdas specifically do not capture anything except the variables specifically mentioned in them, unlike anonymous inner classes, which do capture the enclosing class object if they're defined in an instance method.

Upvotes: 1

Related Questions