Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
71 lines (61 sloc) 2.32 KB
;; 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 (
;; 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}
(: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
(defonce ^:private ^ConcurrentSkipListMap timeouts-map
(def ^:const TIMEOUT_RESOLUTION_MS 10)
(deftype TimeoutQueueEntry [channel ^long timestamp]
(getDelay [this time-unit]
(.convert time-unit
(- timestamp (System/currentTimeMillis))
[this other]
(let [ostamp (.timestamp ^TimeoutQueueEntry other)]
(if (< timestamp ostamp)
(if (= timestamp ostamp)
(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))
(defonce timeout-daemon
(doto (Thread. ^Runnable timeout-worker "clojure.core.async.timers/timeout-daemon")
(.setDaemon true)
(defn timeout
"returns a channel that will close after msecs"
[^long msecs]
(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)
You can’t perform that action at this time.