1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
package garbage;
import java.io.Closeable;
import java.util.ArrayList;
/**
* This code to try to understand a GC strategy.
* IMHO the first object in the main should be reclaimed: it is not!
* why?
* I suspect a bug in the mark and sweep due to cycles ....
*/
public class TestReachable {
/*
* these object are not immmediately garbaged since they are referenced
* from a static ArrayList
*/
static class Closer implements Closeable {
Object thing ;
Closer(Object thing ){
this.thing = thing ;
}
public void close() {
System.out.println("CLOSING");
}
}
static class SafeCloser {
static ArrayList<Closer> closerList = new ArrayList<Closer>() ;
Closer closer ;
SafeCloser(Closer clos) {
this.closer = clos ;
closerList.add(clos) ;
}
public void finalize() {
System.out.println("FINALIZE safeCloser");
closerList.remove(closer) ;
closer.close() ;
}
}
static class ReclaimableObject {
public void finalize() {
System.out.println("FINALIZE A "
+ name + " ;thing : " + thing +" ; safe: " + safe) ;
}
Object thing ;
Closer closer ;
SafeCloser safe ;
String name ;
ReclaimableObject (String name ,boolean withObject, boolean withSafe) {
this.name = name ;
if(withObject) {
this.thing = new Object() ;
}
this.closer = new Closer(thing) ;
if(withSafe) {
this.safe = new SafeCloser(closer) ;
}
}
}
public static void main(String[] args) throws Exception {
// this object will NOT be reclaimed
ReclaimableObject object = new ReclaimableObject("ONE" ,true, true) ;
object = null ;
// this object will be reclaimed
ReclaimableObject object2 = new ReclaimableObject("TWO" ,false, true) ;
object2 = null ; // this object will be reclaimed
ReclaimableObject object3 = new ReclaimableObject("THREE", true, false) ;
object3 = null ;
for(int ix = 0 ; ix < 10000 ; ix++) {
long[] array = new long[1000] ;
}
Thread.sleep(3000L );
System.out.println("MID WAY");
// this object WILL be reclaimed !!!!! (go figure!)
object= new ReclaimableObject("ONE-2" ,true, true) ;
object= null ;
// this object will be reclaimed
object2 = new ReclaimableObject("TWO-2" ,false, true) ;
object2 = null ;
// this object will be reclaimed
object3 = new ReclaimableObject("THREE-2", true, false) ;
object3 = null ;
for(int ix = 0 ; ix < 10000 ; ix++) {
long[] array = new long[1000] ;
}
Thread.sleep(3000L );
System.out.println("THE END");
}
} |
Partager