最近在看 RocketMQ 的源碼,但是看不懂這段代碼。為什么這段代碼可以阻止gc?https://github.com/apache/rocketmq/blob/master/store/src/main/java/org/apache/rocketmq/store/MappedFile.javafor (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 回答

翻翻過去那場雪
TA貢獻2065條經驗 獲得超14個贊
它不是。
線程的睡眠文檔僅說明:
使當前執行的線程在指定的毫秒數內休眠(暫時停止執行),具體取決于系統計時器和調度程序的精度和準確性。該線程不會失去任何監視器的所有權。
這意味著它會對垃圾收集器的行為產生副作用。
通過調用Thread.sleep(0)
,您(可能(它是 0,因此實現甚至可以忽略它))切換上下文,并且可以選擇并行 GC 線程來清理其他引用。次要的副作用是您可能會更頻繁地運行 GC - 可以防止長時間運行的垃圾收集(您增加了每 1000 次迭代運行 GC 的機會)。
添加回答
舉報
0/150
提交
取消