aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/concurrent/SystemTimer.java
blob: 7e32ca25dc4a5c1ff57d8c42eda249655db57a9c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * This is an implementation of {@link Timer} that is backed by an actual system timer.
 *
 * @author Simon Thoresen Hult
 */
public enum SystemTimer implements Timer {

    INSTANCE;

    private volatile long millis;

    private SystemTimer() {
        millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
        Thread thread = new Thread() {

            @Override
            public void run() {
                while (true) {
                    millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            }
        };
        thread.setDaemon(true);
        thread.start();
    }

    @Override
    public long milliTime() {
        return millis;
    }
}