Skip to content

Instantly share code, notes, and snippets.

@SLIB53
Created March 6, 2017 04:33
Show Gist options
  • Save SLIB53/11a4b74bd45a37df500ae5b7df468a44 to your computer and use it in GitHub Desktop.
Save SLIB53/11a4b74bd45a37df500ae5b7df468a44 to your computer and use it in GitHub Desktop.
Does Java garbage collect unreachable objects with cyclical references? (TL;DR: YES)
/*
Question:
------------------------------------------------------------------------
In the function FooUtil.Bang(), will Java delete objects a and b?
Answer:
------------------------------------------------------------------------
Yes. Java garbage collector sees that it is unreachable. GC is not
simply a reference counter.
src: http://stackoverflow.com/questions/1910194/how-does-java-garbage-collection-work-with-circular-references#1910203
*/
public class Foo
{
Foo other;
public void setOther(Foo f) { other = f; }
}
public class FooUtil
{
/*
Creates two Foo with a strong reference to each other,
then exits scope with returning any reference, making created objects
in the method inaccessible.
*/
public static void Bang()
{
Foo a = new Foo();
Foo b = new Foo();
// Creates doubly linked strong reference between a and b
a.setOtherFoo(b);
b.setOtherFoo(a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment