相关疑难解决方法(0)

System.currentTimeMillis是否总是返回值> =之前的调用?

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#currentTimeMillis()说:

以毫秒为单位返回当前时间.请注意,虽然返回值的时间单位是毫秒,但值的粒度取决于底层操作系统,并且可能更大.例如,许多操作系统以几十毫秒为单位测量时间.

我不清楚我是否保证这段代码将始终打印不断增加(或相同)的数字.

while (1) { 
    System.out.println(System.currentTimeMillis() );
}
Run Code Online (Sandbox Code Playgroud)

java linux

45
推荐指数
4
解决办法
1万
查看次数

Java中是否存在一致的(单调)Clock实现?

默认的java.time.Clock实现基于System.currentTimeMillis().正如这里所讨论的那样, 单调增加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());
Run Code Online (Sandbox Code Playgroud)

然后,当人们不能仅依靠一个方向的时间时,就不可能执行时间敏感的事情,例如记录和分析事件历史.

上述帖子说System.nanoTime()是单调的(如果底层系统支持它).所以,如果我想将我的代码基于java.time API,我需要内部使用nanoTime的Clock来确保单向流动的时间.也许这样的事情会起作用.或者不是吗?

public class MyClock() extends java.time.Clock {

    private final long adjustment;

    public MyClock() {
        long cpuTimeMillis = System.nanoTime()/1000000;
        long systemTimeMillis = …
Run Code Online (Sandbox Code Playgroud)

java java-8 java-time

24
推荐指数
1
解决办法
4848
查看次数

标签 统计

java ×2

java-8 ×1

java-time ×1

linux ×1