First of all, allow me to explain a “behaviour” that I observed, then I will ask in “Example” section.
Inner-class-reference behaviour
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).
In other words, or in other programming-languages, where “reference-counters” are often used (unlike Java?);
We could achieve such behaviour if owner-class and all inner-classes share the same reference-counter. Where just like above, even if we only keep a single reference to inner-class, owner-class is kept as well.
Example (background and question)
My previous logic, which used above said behaviour, was something like:
public class WebApi { public UserApi user = new UserApi(); public PostApi post = new PostApi(); protected String post(String url, String json) { // ... } public class UserApi { public void login() { WebApi.this.post(...); } public void logout() { WebApi.this.post(...); } // ... } public class PostApi { // ... } }
Then day by day the project did grow, till each of UserApi
and PostApi
classes deserved their own separate files (instead of being inner-classes of one huge file).
How can we implement above described “Inner-class-reference
” behaviour for external classes?
Advertisement
Answer
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.