默认java.time.Clock实现基于System.currentTimeMillis()。如这里所讨论的,
Monotonically increasing time in Java?,
它不能保证是单调的。
事实上,我经常遇到一个情况,系统时间自动调整到几秒钟,而java时钟也跳回来。
//now() returns 2016-01-13T22:34:05.681Z
order.setCreationTime(Instant.now());
//... something happens, order gets cancelled
//now() returns 2016-01-13T22:34:03.123Z
//which is a few seconds before the former one,
//even though the call was performed later - in any reasonable sense.
//The recorded history of events is obviously inconsistent with the real world.
order.setCancelationTime(Instant.now());
当不能依赖时间只在一个方向上时,不可能执行时间敏感的事情,例如记录和分析事件历史。
上述帖子说System.nanoTime()是单调的(如果底层系统支持它)。所以,如果我想将我的代码放在java.time API上,那我需要在内部使用nanoTime的Clock来确保单向流程。也许这样的事情会起作用。还是不行?
public class MyClock() extends java.time.Clock { </