troubleshooting Question

Using Factory method to prevent this from escaping during construction

Avatar of Rohit Bajaj
Rohit BajajFlag for India asked on
Java
3 Comments1 Solution105 ViewsLast Modified:
Hi,
Here is an example from Java concurrency in practice :

Screen-Shot-2019-03-13-at-6.26.39-PM.png
public class ThisEscape {
    public ThisEscape(EventSource source) {
} }
source.registerListener(
    new EventListener() {
        public void onEvent(Event e) {
            doSomething(e);
} });
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) {
                doSomething(e);
} };
}
    public static SafeListener newInstance(EventSource source) {
        SafeListener safe = new SafeListener();
        source.registerListener(safe.listener);
        return safe;
} }

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.

Thanks
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 3 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros