views:

163

answers:

3

Goetz's Java Concurrency in Practice, page 41, mentions how this reference can escape during construction. A "don't do this" example:

public class ThisEscape {
    public ThisEscape(EventSource source) {
        source.registerListener(
            new EventListener() {
                public void onEvent(Event e) {
                    doSomething(e);
                }
            });
    }
}

Here this is "escaping" via the fact that doSomething(e) refers to the enclosing ThisEscape instance. The situation can be fixed by using static factory methods (first construct the plain object, then register the listener) instead of public constructors (doing all the work). The book goes on:

Publishing an object from within its constructor can publish an incompletely constructed object. This is true even if the publication is the last statement in the constructor. If the this reference escapes during construction, the object is considered not properly constructed.

I don't quite get this. If the publication is the last statement in the constructor, hasn't all the constructing work been done before that? How come is this not valid by then? Apparently there's some voodoo going on after that, but what?

+1  A: 

There is a small but finite time between the registerListener ending and the constructor returning. Another thread could use come in at that time and attempt to call doSomething(). If the runtime didn't return straight to your code at that time, the object could be in a invalid state.

I'm not sure of java really but one example I can think of is where possibly the runtime relocates the instance before returning to you.

Its a small chance I grant you.

Preet Sangha
+7  A: 

The end of a constructor is a special place in terms of concurrency, with respect to final fields. From section 17.5 of the Java Language Specification:

An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

The usage model for final fields is a simple one. Set the final fields for an object in that object's constructor. Do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are.

In other words, your listener could end up seeing final fields with their default values if it examines the object in another thread. This wouldn't happen if listener registration happened after the constructor has completed.

In terms of what's going on, I suspect there's an implicit memory barrier at the very end of a constructor, making sure that all threads "see" the new data; without that memory barrier having been applied, there could be problems.

Jon Skeet
Wow, it's surprising that `final` fields, which usually are considered concurrency friendly, are the the culprit in this case!
Joonas Pulakka
@Joonas: That's the rub - they're concurrency-friendly *if you make sure the reference doesn't escape from the constructor*. In most cases that's a pretty small price to pay.
Jon Skeet
Actually, this applies to any fields, not just final ones.
Stephen C
By the way; would it suffice to make another simple constructor that initializes all the fields, and then call `this()` in the beginning of the more complex constructor that leaks `this`? Would it be analogous to a factory method?
Joonas Pulakka
I made a separate question of the previous comment: http://stackoverflow.com/questions/2513841/how-do-jvms-implicit-memory-barriers-behave-when-chaining-constructors
Joonas Pulakka
@Stephen C: If you look at the spec link, you'll see it's only specifically called out for final fields.
Jon Skeet
+5  A: 

Another problem arises when you subclass ThisEscape, and the child class invokes this consructor. The implicit this reference in the EventListener would have an incompletely constructed object.

Rob Heiser
Good call. In particular this could create problems if the subclass overrides virtual methods from `ThisEscape` - those overridden methods could be called before the state they require has been set up.
Jon Skeet
This is true, but off-topic.
Stephen C
@Stephen C: I think this is quite a good point, definitely not off-topic.
Joonas Pulakka