From 083e41256b60d570086adf28364c0232b612641c Mon Sep 17 00:00:00 2001 From: Daniel Compton Date: Tue, 27 Nov 2018 10:00:08 +1300 Subject: [PATCH] Use nanoTime instead of currentTimeMillis for elapsed time System/currentTimeMillis is not guaranteed to progress monotonically. NTP shifts, leap seconds, and manual system time changes can all cause elapsed time calculations to be incorrect if you use currentTimeMillis. nanoTime is always calculated against a fixed point and proceeds monotonically. https://go.googlesource.com/proposal/+/master/design/12914-monotonic.md has a good discussion on monotonic time. --- src/durable_queue.clj | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/durable_queue.clj b/src/durable_queue.clj index 55f121f..9f905aa 100644 --- a/src/durable_queue.clj +++ b/src/durable_queue.clj @@ -567,10 +567,10 @@ (while (.get ref) (when-let [q (.get ref)] (try - (let [start (System/currentTimeMillis)] + (let [start (System/nanoTime)] (fsync q) - (let [end (System/currentTimeMillis)] - (Thread/sleep (max 0 (- fsync-interval (- end start)))))) + (let [end (System/nanoTime)] + (Thread/sleep (max 0 (- (* 1000000 fsync-interval) (- end start)))))) (catch Throwable e ))))))) @@ -765,16 +765,16 @@ "Returns a lazy sequence of tasks that can be consumed in `interval` milliseconds. This will terminate after that time has elapsed, even if there are still tasks immediately available." [qs q-name interval] - (let [now (System/currentTimeMillis)] + (let [now (System/nanoTime)] (lazy-seq - (let [now' (System/currentTimeMillis) - remaining (- interval (- now' now))] + (let [now' (System/nanoTime) + remaining (- (* 1000000 interval) (- now' now))] (when (pos? remaining) (let [task (take! qs q-name remaining ::none)] (when-not (= ::none task) (cons task - (interval-task-seq qs q-name (- interval (- (System/currentTimeMillis) now))))))))))) + (interval-task-seq qs q-name (- (* 1000000 interval) (- (System/nanoTime) now))))))))))) (defn complete! "Marks a task as complete."