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
Written by Eduard Bondarenko
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Clojure
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#