2

I am doing something related with thread with clojure.

Now I am working in REPL, write and update code in REPL.

My problem is, sometime there will be some futures left running. And I lost the ref by some kind of mistakes. My only way to stop them is restart the repl.

I want to know is there any ways to stop the running futures(threads) if I have no ref on them?

Mavlarn
  • 3,807
  • 2
  • 37
  • 57

1 Answers1

2

Clojure public API provides the only way you can stop running futures which is the following:

(shutdown-agents)

But that will not interrupt your future jobs. Instead of that you can interrupt them with

(import 'clojure.lang.Agent)
(.shutdownNow Agent/soloExecutor)

But please keep in mind that after described operations your Agent/soloExecutor will not accept new tasks. One of the ways how to deal with it is to reassign soloExecutor java field in Agent class. Hopefully it's public and not final.

(import 'java.util.concurrent.Executors) 
(set! Agent/soloExecutor (Executors/newCachedThreadPool)) ;; in original clojure version thread pool is created with thread factory, but that createThreadFactory method is private, anyways for your purposes this code may work just fine without any thread factories.

(future (Thread/sleep 1000) (println "done") 100) ;; now works fine

But in my opinion it is not recommended way to make things in repl. It's way better not to lose your future references.

hsestupin
  • 1,115
  • 10
  • 19
  • I tried it in repl, but after I call shutdown, the future seems to be running still. And if I press enter , the repl will exit. Anyway, thanks for the answer about agent and soloExecutor. – Mavlarn Jan 29 '14 at 03:21