Java scheduled executor accuracy

前端 未结 2 2092
独厮守ぢ
独厮守ぢ 2021-02-14 05:53

There is a peculiarity that I encountered while using Java scheduled executors and was wondering if what I experienced is normal.

I need to schedule tasks that execute a

相关标签:
2条回答
  • 2021-02-14 06:16

    The scheduled executor service uses System.nanoTime which doesn't drift as much as currentTimeMillis. Except if you are running on an XP system with more than one CPU socket. There is a bug in XP where the OS call System.nanoTime() uses is not consistent between sockets so as the thread switches which socket it is running on, you can expect to see this jumping around. (This is not a problem on Vista/7)

    On a Linux system with one socket your program reports 0 - 3 ms drift.

    Try this program.

    public static void main(String... args) throws Exception {
        long start = System.nanoTime();
        long time = start;
        while(time < start + 3e10) {
            long now = System.nanoTime();
            if (now < time || now > time + 50000) {
                System.out.println(now - time);
                now = System.nanoTime();
            }
            time = now;
        }
    }
    

    On an i7 system I see approx 10 jumps of up to 2 ms. If I use the machine I see more. What I expect you might see is large negative and positive timings.

    0 讨论(0)
  • 2021-02-14 06:19

    Seems normal to me, it varies in the range of 5000/2. In stead of format + println you should try a fast logging, so the overhead drift of println is not measured. Would be interesting.

    0 讨论(0)
提交回复
热议问题