Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Clojure fork-join example
(ns fork-join-recur
(:import [java.util.concurrent ForkJoinPool
ForkJoinWorkerThread ForkJoinTask RecursiveTask]))
;; API
;; ===
(def ^:dynamic ^ForkJoinPool *pool* (ForkJoinPool/commonPool))
(defmacro fork [& body]
`(let [^ForkJoinTask task# (proxy [RecursiveTask] []
(compute []
(do ~@body)))]
(if (ForkJoinTask/inForkJoinPool)
(.fork task#)
(.execute *pool* task#))
task#))
(defn join [^ForkJoinTask task]
(.join task))
;; Test
;; ====
(defn rec:factorial [n]
(fork
(if (< n 2)
1
(*' n (join (rec:factorial (dec n)))))))
(defn factorial [n]
(join (rec:factorial n)))
#_(
(factorial 5) ;; => 120
(factorial 5000) ;; => StackOverflow!
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.