Java和垃圾收集中的自定义Iterables

时间:2017-09-08 23:36:49

标签: java garbage-collection

假设我有一个自定义迭代器:

class CustomIterator implements Iterator<CustomObject> {

        @Override
        public Object next() {
              Iterator<Things> readResults = readFromApi();
              return new CustomObject(readResults);
        }

        ...other stuff
}

然后我实现了一个自定义的Iterable

class CustomIterable implements Iterable<CustomObject> {

        CustomIterator<CustomObject> iterator;

        public CustomIterable(final CustomIterator<CustomObject> cursorIterator) {
                  this.iterator = cursorIterator;
        }

        @Override
        public Iterator<CustomObject> iterator() {
              return iterator;
        }

        ... other stuff.
}

然后我在Java中为每个循环使用我的自定义iterable,即

for(CustomObject obj : customIterable) {
    readObj(obj);
    //Nothing is done in readObj that creates another reference to the object. 
    //The CustomObject is read once and then never used again.
}

通过next()方法实例化的每个CustomObject是否会在每个循环进入下一帧后获得Garbage Collected?

1 个答案:

答案 0 :(得分:0)

所以我查看了JStat报告,看起来该对象没有收集垃圾。

这是我的输出。

我基本上写了一个测试

public void testThisBehavior() {
    final Iterable<CustomObject> customIterable = createCustomIterable(); //Should iterate over 3 objects

    for(final CustomObject obj : customIterable) {
        System.out.println(obj);
    }
}

然后我在每个循环行设置一个断点,然后将JStat连接到此过程并开始每10毫秒轮询一次。

我注意到我的伊甸园空间上升,而我的GCT从未增加,尽管经历了迭代。

    S0C    S1C    S0U    S1U      EC       EU        OC         OU       MC     MU    CCSC   CCSU   YGC     YGCT    FGC    FGCT     GCT   

    ... This was the usages when I hit my breakpoint.
    20992.0 14336.0  0.0   14317.6 274432.0 212415.4  243712.0   37918.2   71936.0 70562.4 8960.0 8595.9      9    0.069   3      0.150    0.219
    ... This was the first object getting created I believe after I pressed run, the EU went up but GCT never increase.
    20992.0 14336.0  0.0   14317.6 274432.0 217920.9  243712.0   37918.2   71936.0 70562.4 8960.0 8595.9      9    0.069   3      0.150    0.219
    ... This was the second object getting created
    20992.0 14336.0  0.0   14317.6 274432.0 224798.6  243712.0   37918.2   71936.0 70562.4 8960.0 8595.9      9    0.069   3      0.150    0.219

    ... This was the third object getting created I believe
    20992.0 14336.0  0.0   14317.6 274432.0 244026.5  243712.0   37918.2   71936.0 70562.4 8960.0 8595.9      9    0.069   3      0.150    0.219

我注意到在整个测试过程中,GCT从未改变,尽管轮询很频繁,所以我认为垃圾收集器没有收集对象。我认为这是有道理的,因为它必须保存这样一个事实:一旦它到达终点就不再有了,这意味着无论加载的东西已经被初始化了。