[Solved] Implement inner-class-like reference behaviour? [closed]


In Java we can have (non-static) inner-classes, which seem to “behave” like having a strong-reference to their container-class and/or owner-class, but without causing memory-leak.

I mean, I observed that even if both owner-class and inner-class keep strong-reference to each other, the classes are garbage-collected anyway (once no external class references them, although having reference-recursion).

Yes, that’s how references work in Java: if an object is reachable, then it’s retained, and if not, then it’s (eventually) garbage-collected.

But how can we implement above described “Inner-class-reference” behaviour for external classes?

You don’t need to do anything special: just give UserApi a field of type WebApi, and initialize it in the constructor.

Java’s reference-tracing and garbage collection will ensure that, as long as any reachable UserApi instance holds a reference to a given WebApi instance, the WebApi instance is also considered reachable, and hence retained.

6

solved Implement inner-class-like reference behaviour? [closed]