(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