java垃圾收集器未按预期工作

java垃圾收集器未按预期工作,java,garbage-collection,heap,Java,Garbage Collection,Heap,我的问题很简单。。如果在任何机器上运行以下程序,堆将很快填满。那么为什么GC的速度不够快,无法释放内存呢。 当堆里装满了所有的东西 “新的未使用对象”。为什么他们会粘在堆里 public class TestGc { public String name; public TestGc next; public TestGc(String name) { this.name = name; } public static TestGc create(String nm, int l

我的问题很简单。。如果在任何机器上运行以下程序,堆将很快填满。那么为什么GC的速度不够快,无法释放内存呢。 当堆里装满了所有的东西 “新的未使用对象”。为什么他们会粘在堆里

public class TestGc {

public String name;

public TestGc next;

public TestGc(String name) {
    this.name = name;
}

public static TestGc create(String nm, int len) {
    TestGc[] tmp = new TestGc[len];
    TestGc prev = null;
    for (int i = 0; i < len; i++) {
        TestGc cur = new TestGc(nm + i);
        tmp[i] = cur;
        if (prev != null)
            prev.next = cur;

        prev = cur;
    }
    return tmp[0];
}

public static void main(String[] args) {
    if (args.length != 1) {
        System.err.println("Usage: TestGc <number of roots");
        return;
    }

    int num = Integer.valueOf(args[0]);

    long start = System.currentTimeMillis();

    TestGc[] arr = new TestGc[num];
    for (int i = 0, j = 0; i < 1000; i++, j++) {
        if (j == num)
            j = 0;
        String nm = "root_" + i + "_";
        System.out.println("******** " + nm);
        arr[j] = create(nm, 1000000);
    }
    double duration = (System.currentTimeMillis() - start) / 1000.0;
    System.out.println("******** duration " + duration + " sec.");
}
这个例子是从这里复制过来的。

之所以发生这种情况,是因为除了
create
方法中
tmp
引用的数组之外,所有对象都是可访问的,所以GC不应该处理它们

因为您将
TestGc
实例分配给
arr
,所以在循环的每次迭代中仍然可以访问它们。你为什么要这么做?
java -Xmx23g -Xms23g -server -XX:+UseG1GC -XX:+PrintGCDateStamps -XX:+PrintGCDetails TestGc 150