Minor improvement to anonymous classes

Liam Miller-Cushon cushon at google.com
Sat Jul 31 19:43:36 UTC 2021

On Sat, Jul 31, 2021 at 11:25 AM Remi Forax <forax at univ-mlv.fr> wrote:

> > Any similar limitations to consider loosening at this time?
> > Are there things with generics you can do with lambdas
> > and named ICs but not AICs?
> There is a similar limitation, anonymous classes and local classes always
> capture the enclosing "this" even if they do not use it,
> so when you use an anonymous class, the lifetime of the enclosing this is
> extended for no good reason.
> The usual issue it to have a code that relies on the finalizer to close a
> system resource (which is not a good idea) that fails to close the resource
> because the is captured by the anonymous class. Lambdas do not have this
> weird behavior.
> We have discussed about allowing static in front of a local class but
> there is no way to ask for a static anonymous class.

I think it'd be nice to have a way to get explicitly static anonymous
classes, but I haven't weighed the tradeoffs very carefully.

Another option that gets some of the benefit and doesn't require a spec
change is to omit the reference to the enclosing instance if it is unused.
We've been doing that successfully for a few years at Google. There was
some minor compatibility impact to code using reflection to access the
synthetic field that stores the reference to the enclosing instance, but
that was very rare, and the benefit is that it avoids some memory leaks.

I found a discussion in JDK-6324535
<https://bugs.openjdk.java.net/browse/JDK-6324535> that touched on this,
and mentioned the various options (static anonymous classes, optimizing
away the enclosing instance reference).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20210731/3b963e2f/attachment-0001.htm>

More information about the amber-spec-experts mailing list