Welcome! Please see the About page for a little more info on how this works.

0 votes
in Refs, agents, atoms by
edited by
(defn tid []                                                        
  [(.getName (Thread/currentThread))                                                        
   (.getId (Thread/currentThread))])

   (defn atomize                                                   
  [f data]                                                                                  
  (let [atomix (atom [])                                                                    
        pool (Executors/newFixedThreadPool 12)                                              
        tasks (map                                                                          
               (fn [datum]                                                                  
                 (fn []                                                                     
                   (swap! atomix conj [(f datum) (tid)])))                                  
    (doseq [future (.invokeAll pool tasks)]                                                 
      (.get future  10 TimeUnit/MILLISECONDS ))                                             
    (.shutdown pool)                                                                        

I can't figure out where to place a `sleep` to force a timeout. 
You're gonna love `clojure.core/pmap` - but if I understand your question correctly, maybe the sleep goes in `f`?
Unfortunately not.  It bravely returns the vector. I didn’t want to reinvent pmap  

1 Answer

+2 votes

Hard to tell exactly what your question is, but my guess is you want the execution of the future to stop if it doesn't complete in a certain amount of time.

.get of course does not do this, the timeout for .get is a timeout on the operation of waiting for the result of the future, not a timeout on the future itself.

you could pair .get with a timeout and future-cancel to maybe get something like that, but even future-cancel is not guaranteed to stop a running thread. And the jvm authors keep removing ways to uncooperatively stop a running a thread.

The best way is to write the process that is running in such a way as to cooperate with being shutdown, either waiting for some signal to shutdown or stopping execution after some time limit has been reached. This requires a fair bit of communication between processes and sometimes requires processes to be able to wait on multiple threads at once (wait for a message from another process and also wait for the signal to stop). core.async provides some nice primitives for that.

“…timeout on the future itself…”

I begin to see it clearly now - less or more. Thanks.