Created
March 10, 2012 15:30
-
-
Save sciolizer/2011793 to your computer and use it in GitHub Desktop.
Java garbage collection of circular references
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
jball@localhost:~/tmp/javaref$ java -version | |
java version "1.6.0_30" | |
Java(TM) SE Runtime Environment (build 1.6.0_30-b12) | |
Java HotSpot(TM) 64-Bit Server VM (build 20.5-b03, mixed mode) | |
jball@localhost:~/tmp/javaref$ java JavaRef | |
JavaRef$A@4fe5e2c3 | |
JavaRef$Dog@7d8a992f | |
JavaRef$Tail@164f1d0d | |
JavaRef$A@8dc8569 | |
JavaRef$Dog@64c3c749 | |
JavaRef$Tail@7150bd4d | |
JavaRef$A@3ce53108 | |
JavaRef$Dog@6af62373 | |
JavaRef$Tail@459189e1 | |
collecting tail | |
collecting tail | |
JavaRef$A@527c6768 | |
collecting a | |
JavaRef$Dog@65690726 | |
JavaRef$Tail@525483cd | |
collecting dog | |
shutting down | |
collecting dog | |
collecting a | |
collecting tail | |
collecting dog | |
collecting a | |
collecting tail | |
collecting dog | |
collecting a | |
*/ | |
public class JavaRef { | |
public static class A { | |
public Dog dog; | |
protected void finalize() { | |
System.out.println("collecting a"); | |
} | |
} | |
public static class Dog { | |
public Tail tail; | |
protected void finalize() { | |
System.out.println("collecting dog"); | |
} | |
} | |
public static class Tail { | |
public Dog dog; | |
protected void finalize() { | |
System.out.println("collecting tail"); | |
} | |
} | |
public static void main(String[] args) { | |
for (int i = 0; i < 4; i++) { | |
createGarbage(); | |
System.gc(); | |
} | |
System.out.println("shutting down"); | |
} | |
private static void createGarbage() { | |
A a = new A(); | |
Dog dog = new Dog(); | |
Tail tail = new Tail(); | |
a.dog = dog; | |
dog.tail = tail; | |
tail.dog = dog; | |
System.out.println(a); | |
System.out.println(dog); | |
System.out.println(tail); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment