Last Updated: February 25, 2016
·
1.403K
· edbond

Clojure with-timeout macros

(ns timeout
  (:import [java.util.concurrent TimeoutException]))

(defmacro with-timeout
  [msec & body]
  `(let [f# (future (do ~@body))
         v# (gensym)
         result# (deref f# ~msec v#)]
    (if (= v# result#)
      (do
        (future-cancel f#)
        (throw (TimeoutException.)))
      result#)))
(with-timeout 1000
  (Thread/sleep 40)
  42)
;; returns 42

(with-timeout 1000
  (Thread/sleep 4000)
  42)
;; throws TimeoutException