Using Factory method to prevent this from escaping during construction

Rohit Bajaj
Rohit Bajaj used Ask the Experts™
Here is an example from Java concurrency in practice :

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

Open in new window

As per my understanding
The above code has the following problem :
1) Since we are making an anonymous class it will contain the this object with it.
2) This is done inside a constructor before the constructor completes the execution and so the object may not be in a proper state.
So there could be a case due to very lucky timing that this was extracted out of Evenlistener and its a corrupted this.
Although once the constructor completes i think this should automatically be pointing to the complete object.

Now the book gives another example to avoid this escape of this

public class SafeListener {
    private final EventListener listener;
    private SafeListener() {
        listener = new EventListener() {
            public void onEvent(Event e) {
} };
    public static SafeListener newInstance(EventSource source) {
        SafeListener safe = new SafeListener();
        return safe;
} }

Open in new window

I dont quite understand how this is not escaped here.
Because here again we are using anonymous class to create an object in the same way as earlier.
So here also this should have escaped.
Please clarify.

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2018
In the first case you register the listener before the object is fully created.

In the second case you first create the object and then you register the listener.


1) Yes but this object escapes in the second case also.
2) And in first case even though this object escapes to the listener when in a non completed state.
Still its the object pointer and when the object will be created it will be pointing to the correct one only.

I am thinking that the point of this example was to avoid escaping of this.
But this is getting escaped in both the cases anyway
Distinguished Expert 2018

In the second case it does not escape. The listener is not registered/started until *after* the object is created.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial