删除引用后,GC不会从数组中删除对象

时间:2016-02-27 20:37:01

标签: java garbage-collection

我上课了 Shape

private int refcount = 0;
private static long counter = 0;
private final long id = counter++;
Shape () {
    System.out.println("Create "+ this);
}

public void addRef() { refcount++; }
public void dispose() {
    if (--refcount == 0)
        System.out.println("Delete " + this);
}

@Override
public String toString() { return "Shape "+ id; }

@Override
public void finalize() {
    if (refcount == 0)
        System.out.println("Finalize correctly " + this);
}

和第二类容器

private Shape shape;
private static long counter = 0;
private final long id = counter++;
Container (Shape shape) {
    this.shape = shape;
    this.shape.addRef();
    System.out.println("Create " + this );
}


public void dispose() {
    System.out.println("Delete " + this);
    shape.dispose();
}

@Override
public String toString() { return "Container "+ id; }

@Override   
public void finalize() { System.out.println("Finalize container!"); }

这是我简单的主要代码:

public static void main(String[] args) {
    System.out.println("Start");
    Shape sh = new Shape();
    Container[] cont = { new Container(sh), new Container(sh), new Container(sh) };
    for (Container c : cont)  
        c.dispose();           
    cont = null;
    System.gc();
    System.out.println("Finish");
}

我想知道,为什么我没有收到评论“Finalize container!”?当我删除行:

    for (Container c : cont)
        c.dispose();

程序正常工作 - 我有3次评论“Finalize container”。

1 个答案:

答案 0 :(得分:0)

System.gc()不保证完整的gc,它只是对JVM的最好的建议,不要依赖它。