bounded-worker-pool-pmap
Clojure
(import '[java.util.concurrent Callable Executors ExecutionException Future])
(defn pmap-bounded
"Runs f over coll with at most n workers, returning results in input order."
[n f coll]
(let [pool (Executors/newFixedThreadPool n)
tasks (mapv (fn [x]
(.submit pool ^Callable (reify Callable (call [_] (f x)))))
coll)]
(try
(mapv (fn [^Future t]
(try (.get t) (catch ExecutionException e (throw (.getCause e)))))
tasks)
(finally (.shutdownNow pool)))))