-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathtimers.clj
70 lines (61 loc) · 2.32 KB
/
timers.clj
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
;; Copyright (c) Rich Hickey and contributors. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^{:skip-wiki true}
clojure.core.async.impl.timers
(:require [clojure.core.async.impl.protocols :as impl]
[clojure.core.async.impl.channels :as channels])
(:import [java.util.concurrent DelayQueue Delayed TimeUnit ConcurrentSkipListMap]))
(set! *warn-on-reflection* true)
(defonce ^:private ^DelayQueue timeouts-queue
(DelayQueue.))
(defonce ^:private ^ConcurrentSkipListMap timeouts-map
(ConcurrentSkipListMap.))
(def ^:const TIMEOUT_RESOLUTION_MS 10)
(deftype TimeoutQueueEntry [channel ^long timestamp]
Delayed
(getDelay [this time-unit]
(.convert time-unit
(- timestamp (System/currentTimeMillis))
TimeUnit/MILLISECONDS))
(compareTo
[this other]
(let [ostamp (.timestamp ^TimeoutQueueEntry other)]
(if (< timestamp ostamp)
-1
(if (= timestamp ostamp)
0
1))))
impl/Channel
(close! [this]
(impl/close! channel)))
(defn- timeout-worker
[]
(let [q timeouts-queue]
(loop []
(let [^TimeoutQueueEntry tqe (.take q)]
(.remove timeouts-map (.timestamp tqe) tqe)
(impl/close! tqe))
(recur))))
(defonce timeout-daemon
(delay
(doto (Thread. ^Runnable timeout-worker "clojure.core.async.timers/timeout-daemon")
(.setDaemon true)
(.start))))
(defn timeout
"returns a channel that will close after msecs"
[^long msecs]
@timeout-daemon
(let [timeout (+ (System/currentTimeMillis) msecs)
me (.ceilingEntry timeouts-map timeout)]
(or (when (and me (< (.getKey me) (+ timeout TIMEOUT_RESOLUTION_MS)))
(.channel ^TimeoutQueueEntry (.getValue me)))
(let [timeout-channel (channels/chan nil)
timeout-entry (TimeoutQueueEntry. timeout-channel timeout)]
(.put timeouts-map timeout timeout-entry)
(.put timeouts-queue timeout-entry)
timeout-channel))))