Skip to content

Commit f115a98

Browse files
danielcomptonvedang
authored andcommitted
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. Closes: clj-commons#21
1 parent f076644 commit f115a98

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

src/durable_queue.clj

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -562,10 +562,10 @@
562562
(while (.get ref)
563563
(when-let [q (.get ref)]
564564
(try
565-
(let [start (System/currentTimeMillis)]
565+
(let [start (System/nanoTime)]
566566
(fsync q)
567-
(let [end (System/currentTimeMillis)]
568-
(Thread/sleep (max 0 (- fsync-interval (- end start))))))
567+
(let [end (System/nanoTime)]
568+
(Thread/sleep (max 0 (- (* 1000000 fsync-interval) (- end start))))))
569569
(catch Throwable e
570570
)))))))
571571

@@ -759,16 +759,16 @@
759759
"Returns a lazy sequence of tasks that can be consumed in `interval` milliseconds. This will
760760
terminate after that time has elapsed, even if there are still tasks immediately available."
761761
[qs q-name interval]
762-
(let [now (System/currentTimeMillis)]
762+
(let [now (System/nanoTime)]
763763
(lazy-seq
764-
(let [now' (System/currentTimeMillis)
765-
remaining (- interval (- now' now))]
764+
(let [now' (System/nanoTime)
765+
remaining (- (* 1000000 interval) (- now' now))]
766766
(when (pos? remaining)
767767
(let [task (take! qs q-name remaining ::none)]
768768
(when-not (= ::none task)
769769
(cons
770770
task
771-
(interval-task-seq qs q-name (- interval (- (System/currentTimeMillis) now)))))))))))
771+
(interval-task-seq qs q-name (- (* 1000000 interval) (- (System/nanoTime) now)))))))))))
772772

773773
(defn complete!
774774
"Marks a task as complete."

0 commit comments

Comments
 (0)