So lets say there are two classes:
public class A {
B reference = new B(this) //B isn't garbage collected because A references it
}
public class B {
A reference // A isn't garbage collected because B references it
public B(A ref) {
reference = ref;
}
}
And then a third class creates a new A
object. Then, when it wants to get ride of it, it sets that pointer to null
. Wouldn't there be some weird persistant loop caused by A and B because they both reference each other? Neither can be collected because they keep each other "alive". Or is the JVM too smart for that and realizes that the rest of the program doesn't know about them?
It feels like this might cause some sort of memory leak.
If this is possible, how do you fix it? Bidirectional references are very common in code. There are many cases when object 1 knows about object 2 and object 2 knows about object 1. How do you make sure that they are deleted.
NOTE: I wrote all this in my web browser, so forgive any errors