最近我在RocketMQ中阅读了源代码,但我无法理解这段代码 . 为什么这段代码可以阻止gc?
for (int i = 0, j = 0; i < this.fileSize; i += MappedFile.OS_PAGE_SIZE, j++) {
byteBuffer.put(i, (byte) 0);
// force flush when flush disk type is sync
if (type == FlushDiskType.SYNC_FLUSH) {
if ((i / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE) >= pages) {
flush = i;
mappedByteBuffer.force();
}
}
// prevent gc
if (j % 1000 == 0) {
log.info("j={}, costTime={}", j, System.currentTimeMillis() - time);
time = System.currentTimeMillis();
try {
Thread.sleep(0);
} catch (InterruptedException e) {
log.error("Interrupted", e);
}
}
}
1 回答
它不是 .
Thread的睡眠文档仅说明:
这意味着它可能对垃圾收集器的行为产生副作用 .
通过调用
Thread.sleep(0)
,您(可能(它是0,因此实现甚至可以忽略))切换上下文,并且可以选择并行GC线程来清理其他引用 . 副作用是您可能更频繁地运行GC - 这可以防止长时间运行的垃圾收集(您每增加1000次迭代就会增加GC运行的几率) .