    otherwise the nearest group is used and its range is increased to include the new distance, i.e. its grown"
   (let [v (nearest-group t groups)
         d (distance t v)]
-    
     (if (and (> d threshold) (< (count groups) max-groups))
       (let [m (max-value groups)
             v2 [m (+ m d threshold)]]
         [v2 (conj groups v2)])
       [v  groups])))             
-    
+ 
+
+(defn pool-manager [threshold max-groups start-group pool-create]
+ {:pool-create pool-create 
+  :max-groups max-groups :threshold threshold :pools (ref {}) :groups (ref [start-group])})
+
+(defn default-pool-manager [threshold max-groups start-group pool-size]
+   (pool-manager threshold max-groups start-group #(create-exec-service pool-size)))
+  
+(defn get-pool [{:keys [max-groups threshold pools groups pool-create]} t]
+  "Gets a pool if within the groups, otherwise a new pool is created and returned"
+  (let [[g groups2] (select-group t @groups threshold max-groups)]
+    (dosync 
+      (alter groups (fn [m] groups2))
+      
+	    (if-let [exec (get @pools g)]
+	      exec
+	      (get (alter pools (fn [m] (if (nil? (get m g))
+                                          (assoc m g (pool-create))
+                                          m)))
+             g)))))
+
+

  (reduce (partial nearest t) groups))

(defn max-value [groups]
  (reduce (fn [[a1 a2] [b1 b2]] (max a1 a2 b1 b2)) groups))


(defn select-group [t groups threshold max-groups]

(ns thread-exec.core
  (:import 
    [java.util.concurrent ThreadFactory BlockingQueue Callable ThreadPoolExecutor SynchronousQueue TimeUnit ExecutorService ThreadPoolExecutor$CallerRunsPolicy]))



(defn- create-exec-service [threads]
   (doto (ThreadPoolExecutor. 0 threads 60 TimeUnit/SECONDS (SynchronousQueue.))
     (.setRejectedExecutionHandler  (ThreadPoolExecutor$CallerRunsPolicy.))))
       

(defn abs [n]
  (Math/abs ^int  n))
