// 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;
    }
}

@@ -166,16 +166,81 @@
 imeUnit;
+%0Aimport java.util.logging.Level;%0Aimport java.util.logging.Logger;
 %0A%0A/**%0A *
@@ -438,58 +438,779 @@
 ate 
-volatile long millis;%0A%0A    private SystemTimer() %7B
+static final Logger log = Logger.getLogger(SystemTimer.class.getName());%0A%0A    private volatile long millis;%0A%0A    private static int detectHz() %7B%0A        String hzEnv = System.getenv(%22VESPA_TIMER_HZ%22);%0A        int hz = 1000;%0A        if ((hzEnv != null) && !hzEnv.isBlank()) %7B%0A            try %7B%0A                hz = Integer.parseInt(hzEnv);%0A            %7D catch (NumberFormatException e) %7B%0A                log.log(Level.WARNING, %22Failed parsing VESPA_TIMER_HZ='%22 + hzEnv + %22'%22, e);%0A            %7D%0A        %7D;%0A        hz = Math.min(1000, Math.max(1, hz)); // Capping to valid range %5B1...1000%5Dhz%0A        log.fine(%22vespa-system-timer running at %22 + hz + %22hz. VESPA_TIMER_HZ='%22 + hzEnv + %22'%22);%0A        return hz;%0A    %7D%0A%0A    SystemTimer() %7B%0A        int napTime = 1000 / detectHz();
 %0A   
@@ -1540,17 +1540,23 @@
 d.sleep(
-1
+napTime
 );%0A     
@@ -1729,24 +1729,70 @@
 emon(true);%0A
+        thread.setName(%22vespa-system-timer%22);%0A
         thre

Allow control of vespa-system-timer frequency in the range [1...1000] hz with environment variable VESPA_TIMER_HZ.