Created
October 17, 2016 15:50
-
-
Save AfonsoTsukamoto/942492640f95491c88b1d2a5510f2ffe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns question.pool | |
(:refer-clojure :exclude [take]) | |
(:require | |
[clojure.tools.logging :as log])) | |
(def pool (ref [])) | |
(defn take | |
[pool] | |
(dosync | |
(let [[h & t] @pool] | |
(ref-set pool (vec t)) | |
h))) | |
(defn put | |
[pool value] | |
(dosync | |
(alter pool conj value) | |
nil)) | |
(defn init-with-size | |
[size init-fn & args] | |
(do | |
(log/infof "creating pool with size %s" size) | |
(dotimes [n size] | |
(put pool (apply init-fn args))) | |
pool)) | |
(defmacro with-resource-from-pool | |
[current-pool object-name & body] | |
`(let [~object-name (take ~current-pool)] | |
(try | |
(let [res# ~@body] | |
(put ~current-pool ~object-name) | |
res#) | |
(catch Exception e# | |
(put ~current-pool ~object-name) | |
(log/errorf "Pool exception: %s" e#) | |
(throw e#))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment