sleep
javadoc
Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds, subject to
the precision and accuracy of system timers and schedulers. The thread
does not lose ownership of any monitors.
使当前执行的线程休眠(暂时停止执行)指定的毫秒数,取决于系统计时器和调度程序的精度和准确性。该线程不会失去任何监视器的所有权。
sleep(0)
虽然是sleep 0,但因操作系统时钟精度原因,实际会sleep 几毫秒,不同的系统,精度可能值会不一样。
由于sleep是一个native方法,而native方法在返回到java之后是会进入safepoint,而rocketmq 正是通过sleep(0) 进入安全点来降低了单次gc的时间,但是同时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);
}
}
}
和yield对比
sleep是睡眠了 可以保证没有当前线程的竞争 但是yield不能保证自己没有竞争 也就是说还可能是yield的这个线程重新拿到锁 那就没有什么卵用了