SAM identity or at least equals/hashCode
Peter Levart
peter.levart at marand.si
Tue Jun 21 05:16:53 PDT 2011
On 06/21/11, Rémi Forax wrote:
> >> If you want to refer to the object instance that is the result of SAM
> >> conversion, call that the SAM instance or the SAM object -- which is an
> >> object. (You can't assume much about its identity -- the compiler will
> >> likely make sure that all instances of "stateless" lambdas are really
> >> the same object, a la the "Flyweight" pattern.)
> >>
> > Only stateless? Why?
>
> The idea is that stateless lambda can be constant folded by the compiler
> + VM.
> If lambda are stateful, you just can't.
Can't fold it and assign it to a static final field by itself, yes. But if some meaningfull equals/hashCode is defined either on the SAM instances or somewhere private in the runtime (not exposed via SAM's equals/hashCode), then a canonicalizing cache of weakly referenced instances of SAM objects can be used by lambda expression -> SAM conversion.
>
> > I might have missed that and I'm sure there has been discussion already on this list about the topic, but it was a long time ago. So I thought to ask whether there are any news.
> >
> > The question is: Will SAM objects that lambda expressions are going to be converted to, implement any meaningfull equals/hashCode methods or are those methods going to be inherited from Object (or SAM class).
>
> In the current spec, SAM is currently restricted to interface, so
> equals/hashCode are inherited from Object.
I see the solution as either one of:
- keep equals/hashCode in SAM instances inherited from Object (i.e. identity compare) and provide a private canonicalizing cache of weakly referenced SAM instances as part of runtime.
- don't burden the runtime with a canonicalizing cache of weakly referenced SAM instances, but provide meaningfull equals/hashCode methods on SAM instances that would delegate those two methods to captured state and to the identity of the code that executes lambda body.
those two approaches can be combined (like in java.lang.Integer - cache only stateless lambdas on static final fields inside classes that define methods that execute lambda codes for example, and provide a meaningfull euals/hashCode too)
>
> Rémi
>
Regards, Peter
More information about the lambda-dev
mailing list