1

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?

liuxl
  • 103
  • 5
  • How old is that book? In theory, the inner class has a reference to the outer (or enclosing class) and the outer class has a reference to the inner class - which means both are **never** unreachable for GC (maybe). – Elliott Frisch Aug 11 '17 at 04:31
  • The book said it was bad to do so, made the object escape, and I think it is not about the GC only, so I wondered whether I can access the outer object via reflection if I've got an inner object. – liuxl Aug 11 '17 at 04:39
  • 1
    @ElliottFrisch in case Java used ARC (automatic reference counting) like some programming languages do, you were right, but the JVM uses reachability analysis, so both can be freed of they are not reachable. – Gábor Bakos Aug 11 '17 at 05:55

1 Answers1

0

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).

Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52