How to get an outer class instance with an inner class instance in Java

226 Views Asked by At

In the book Java concurrency in practice, when talking about ways to publish an object, there is a mechanism is to publish an inner class instance, and it is not safe because

inner class instances contain a hidden reference to the enclosing instance

I was wondering how come it is unsafe if you couldn't get the outer class instance through an inner class instance, just because it will effect the GC? I'm confused, whether there is a way to get an outer class instance ,like reflection?

1

There are 1 best solutions below

0
Gábor Bakos On

It will not effect GC as you might think. The JVM uses reachability analysis, not automatic reference counting, so both can be freed when none of them are reachable from the starting main's object graph.

It is unsafe -I guess they meant by publishing as serializing and sending-, because through the reference the outer instance will also be serialized causing larger message and or serialization exception (in case it contains something -non-transient- not serializable member or itself is not serializable).

I am not sure the outer object reference name is standardized in any way, so accessing them through reflection requires some trial and error (and obviously testing).