0

The question is not about concurrency.

I'm reading B. Goetz's Java Concurrency in practice and now I'm at the section 3.2 about object publication. He said

A final mechanism by which an object or its internal state can be published is to publish an inner class instance, as shown in ThisEscape in Listing 3.7.

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

So, I tried to write my own harmful example of such publication. Here it is:

public class InnerPublication {

    public static void main(final String[] args){
        Subscriber s = new Subscriber();
        s.subscribe(new ToPublish(){ });
    }

    public abstract static class ToPublish{ }

    public static class Subscriber{
        public void subscribe(ToPublish tp){
            //How can I use the published enclosing instance to do some harm?
        }
    }
}

Since, anonymous class is always (even in a static context) an inner class, we've got a publication here. But I don't see how I could use the publication to do some harm on the enclosing instance.

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 5
    believe it or not, http://stackoverflow.com/questions/28676796/how-does-this-reference-to-an-outer-class-escape-through-publishing-inner-clas seems to be a duplicate. – tharindu_DG Dec 25 '15 at 07:22
  • @tharindu_DG Cool, thank you. – St.Antario Dec 25 '15 at 07:30
  • 1
    You cannot access the enclosing instance of the anonymous `ToPublish` subclass from the `Subscriber` member class (unless you use reflection). You need to do that from within your anonymous class itself. – Erwin Bolwidt Dec 25 '15 at 07:38

0 Answers0