[concurrency-interest] JLS: finality of "enclosing instance" of inner classes

Joe Bowbeer joe.bowbeer at gmail.com
Mon Mar 15 10:14:26 EDT 2010


The only JLS reference is 15.8.4, right?

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.8.4

There was some discussion on the JavaMemoryModel list in May 2004: "Are
this$x fields final?"

http://www.cs.umd.edu/~pugh/java/memoryModel/archive/2348.html

And there was more discussion in August 2007: "Guarantees for
enclosing-instance references?"

I include a snippet from this discussion below.  If you don't receive a
definitive answer here, I suggest you try posting on JMM.

-----

Jeremy Manson wrote:

Nope.  We never guarantee it.

The fact that these fields happen to be final is just an implementation
artifact.  Relying on this property is relying on the source to bytecode
transformation never changing.

Bart Jacobs wrote:

I may be missing something, but the way I read JLS3, it does guarantee this.
It seems to me that JLS3 guarantees in paragraph 15.8.4 that a qualified
this expression always evaluates to a reference to the appropriate enclosing
instance. The language of JLS3 does not seem to allow for qualified
thisexpressions evaluating to null.

Also, it would be unfortunate if JLS3 did not guarantee this, seeing how
easily it can be implemented, simply by storing the reference in a final
field?

Jeremy Manson wrote:

A qualified this expression does always evaluate to a reference to the
appropriate enclosing instance. Thinking about it, I suppose that probably
does imply that the correct value of this will be seen.  But only "this" --
it doesn't say that fields reachable from this will be seen correctly.

-----


On Mon, Mar 15, 2010 at 4:37 AM, Matthias Ernst wrote:

> Hi,
>
> does the JLS contain any language about the finality of the enclosing
> instance reference? In practice, javac maps the "outer this" to a final
> field "this$0", assigned in the inner class' constructor which would render
> it safely published as of JLS 17.5 ("Final field semantics"). However, I
> couldn't find any language in the spec regarding this.
>
> I stumbled over this looking at how java.util.HashMap constructs its
> collection views lazily:
>
>   960       private Set<Map.Entry<K,V>> entrySet0() {
>   961           Set<Map.Entry<K,V>> es = entrySet;
>   962           return es != null ? es : (entrySet = new EntrySet());
>
>   963       }
>
> (http://www.docjar.com/html/api/java/util/HashMap.java.html)
>
> This is only safe if final field semantics apply to enclosing instances.
>
> Thanks
> Matthias
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20100315/a6428feb/attachment.html>


More information about the Concurrency-interest mailing list