Are lambdas garbage collected?

Tags: , ,



If I’m not mistaken, under certain situations a lambda in Java is generated as an anonymous class instance. For example, in this code the lambda needs to capture a variable from the outside:

final int local = 123456;
list.forEach(x -> System.out.println(x + local));

Does it means that the garbage collector will claim the lambda as an object?

Answer

No it won’t; this is not how lambdas work.

Yes, a class instance is generated; no, it won’t fade out.

A lambda is a call site which is linked using invokedynamic; after the initial linkage is done, the JIT is free to kick in and may, for instance, inline the code. So, your “class instance” is only really a class at the beginning.

If the lambda is a method reference for instance, ultimately the JIT will inline the lambda into an invoke{static,virtual,interface,special} according to what this method reference is. The work done by the JIT is however vendor-dependent.



Source: stackoverflow