I’m reading the book Java Concurrency in Practice. In section 3.2 it talks about escaping outer class while publishing inner classes. Now I’m looking for the syntax that makes it possible. Let’s say we have:
public class ThisEscape {
public Integer i = 47;
public ThisEscape(EventSource source) {
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
});
}
}
If I got it right about escaping outer class, I assume that EventSource somehow can access EventListener enclosing class (in this case ThisEscape). Say we implement EventSource as the following:
public class EventSource {
public void registerListener(EventListener listener) {
// How does it have access to enclosing class of the listener variable i?
}
}
Just how can we have access to the public variable i from registerListener?
Just found a typo. Replaced “EventSource enclosing class” with “EventListener enclosing class”. Fortunately everybody got the right version.
Imagine
EventSourceis written something like this:For the purposes of the memory model it doesn’t matter that it doesn’t have direct access to the
ThisEscapeobject. (It might – reflection, some method onEventListener, in the same package, enabled by some method in the same package, etc.) What matters is that the fields ofThisEscapeare being accessed in some manner, which will likely be thread-unsafe.