在文章DistributedUniqueTimeProvider.currentTimeNanos之后,我检查了https://chronicle.software/unique-timestamp-identifiers/方法的实现。
long time = provider.currentTimeNanos();
long time0 = bytes.readVolatileLong(LAST_TIME);
long timeN = timestampFor(time) + hostId;
if (timeN > time0 && bytes.compareAndSwapLong(LAST_TIME, time0, timeN))
return timeN;
return currentTimeNanosLoop();默认情况下,它使用SystemTimeProvider
如果我们看看net.openhft.chronicle.core.time.SystemTimeProvider#currentTimeNanos的内部
long nowNS = System.nanoTime();
long nowMS = currentTimeMillis() * NANOS_PER_MILLI;
long estimate = nowNS + delta;
if (estimate < nowMS) {
delta = nowMS - nowNS;
return nowMS;
} else if (estimate > nowMS + NANOS_PER_MILLI) {
nowMS += NANOS_PER_MILLI;
delta = nowMS - nowNS;
return nowMS;
}
return estimate;我们可以看到它使用了非易失性的非原子变量。
private long delta = 0;所以问题是:毕竟DistributedUniqueTimeProvider.currentTimeNanos线程安全吗?如果是,那是为什么?
发布于 2022-12-01 14:59:36
delta值是对墙上时钟和单调时钟的差的估计。在最坏的情况下,在不同的线程中,这可能高达1ms,因为总是有至少一次毫秒和纳秒的检查。但是,如果与具有完全内存屏障的DistributedUniqueTimeProvider一起使用,并且它自己执行单调递增的值,它就不会有什么意义。
取消此内存障碍检查的原因是将此操作的成本降低了大约20%。
https://stackoverflow.com/questions/74624868
复制相似问题