Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I letting the 'this' reference escape? (inner class in constructor instantiation, no event listener, no threads)

Tags:

java

I am instantiating an inner class in my constructor but I'm not using it to start threads or as an event listener. For example:

public class Something {

    final InnerSomething innerSomething = new InnerSomething();

    public Something(Param arg) {
        super(arg);
    }

    private class InnerSomething {...}

    ...
}

EDIT: I copied & pasted the code from somewhere else and forgot to delete the "abstract" keyword.

EDIT2: "My" definition of "'this' reference escape" is the one found in the book Java Concurrency in Practice.

With the above code, am I allowing the 'this' reference to "escape"?

like image 368
deinocheirus Avatar asked Oct 20 '25 01:10

deinocheirus


1 Answers

Technically you are since InnerSomething will have a reference to this before Something's constructor returns.

However if you don't publish the reference and don't do anything with it in InnerSomething's constructor, it should not create problems. Note that it would be better to mark innerSomething private as one could access this through the package-private field.

If you refer to JCiP #3.2.1, they state:

More specifically, the this reference should not escape from the thread until after the constructor returns. The this reference can be stored somewhere by the constructor so long as it is not used by another thread until after construction.

like image 104
assylias Avatar answered Oct 21 '25 14:10

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!