Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java lambda anonymous object reused?

As of the current JDK 1.8 implementation, it builds an anonymous object to hold the lambda function and calls the function on such object. Is this anonymous object reused in each call, or is an object re-created each time?

like image 726
Alex Suo Avatar asked Feb 11 '15 10:02

Alex Suo


1 Answers

It may be re-used, it may not.

From JLS 15.27.4:

Either a new instance of a class with the properties below is allocated and initialized, or an existing instance of a class with the properties below is referenced.

You cannot depend on it to be one or the other. The compiler and/or runtime can choose the one that will give the best result. (This is one of the benefits of lambdas over anonymous classes -- because every time you use new, even on an anonymous class, it is guaranteed to be a new object, they are unable to optimize it by re-using it, even though 99% of the time you don't care if they are the same object or not.)

In the case where the lambda captures variables from the surrounding scope, it is generally not possible to re-use the object because the value of the captured variables is state stored in the lambda object, and each time the lambda is evaluated (even if it's the same lambda in source code), it may capture different values of the captured variables. Only if the compiler can somehow guarantee that two particular evaluations of the lambda must capture the exact same value of variables, can the compiler re-use the object.

In the case where the lambda does not capture any variables, then all instantiations of that lambda are identical in behavior. So in this case, a single object can be re-used for all evaluations of that lambda. I believe that the current implementation of Java does only allocate one copy for the duration of the program in this case. But this is just an optimization that is implementation-dependent.

like image 101
newacct Avatar answered Oct 13 '22 02:10

newacct