Skip to content

Instantly share code, notes, and snippets.

@AfonsoTsukamoto
Created October 17, 2016 15:50
Show Gist options
  • Save AfonsoTsukamoto/942492640f95491c88b1d2a5510f2ffe to your computer and use it in GitHub Desktop.
Save AfonsoTsukamoto/942492640f95491c88b1d2a5510f2ffe to your computer and use it in GitHub Desktop.
(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