When lambdas become objects

Remi Forax forax at univ-mlv.fr
Wed Nov 28 03:36:31 PST 2012

On 11/28/2012 06:05 AM, Brian Goetz wrote:
>>> Implementations are permitted to do so, and ours (mostly) does.  But this is not guaranteed and you should not assume that it does.
>> When you say I shouldn't assume that it does, you mean that I
>> shouldn't rely on that behavior for my program's correctness, right?
> Correct.

Technically the implementation may create two lambda objects if two 
threads reach at the same time the code that creates the lambda object 
once but the implementation will always return only one of the two. 
Because creating a lambda object has no side effect it's not a problem.
That's a reason why we don't support lambda that implements abstract 
class, because in that case, the constructor of the abstract class
should have been called twice.

>>>> Does every invocation of isFunActivity() return a separate Predicate
>>>> instance?  Or, would a given FunDetector instance always return the same
>>>> Predicate instance?
>>> Because isFun is an instance method, you have to capture the receiver variable 'this', so each capture is likely to result in a new object. (Note you could have written this both more compactly and more explicitly as "return this::isFun".)
>> Are there plans to eventually do some sort of instance-level caching &
>> reuse of these lambdas, when the lambdas only capture 'this', either
>> later in the JDK8 development cycle or else in a future version of
>> Java?
> It's definitely out of scope for 8.  While its possible we might
> consider things like this in the future, realistically there are much
> higher-leverage optimizations where we'd likely put our efforts first.
> (Such as, reducing the cost of lambda capture in the first place.)

yes, caching objects is so 2000 :)
There are better optimizations based on the idea that the VM should not 
create the lambda object if not necessary,
so a call to the lambda method through the lambda object will be 
replaced by a direct call to the lambda method without creating the 
lambda object, reducing the cost of the lambda capture to zero.


More information about the lambda-dev mailing list