Skip to content

Instantly share code, notes, and snippets.

Created October 11, 2018 16:50
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#))
(defn join [^ForkJoinTask task]
(.join task))
;; Test
;; ====
(defn rec:factorial [n]
(if (< n 2)
(*' 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