Skip to content

Instantly share code, notes, and snippets.

@mikeananev
Last active October 15, 2023 01:23
Show Gist options
  • Save mikeananev/fd342b1b4d3c606587f9f0d657923b91 to your computer and use it in GitHub Desktop.
Save mikeananev/fd342b1b4d3c606587f9f0d657923b91 to your computer and use it in GitHub Desktop.
Java 19 virtual threads and Clojure
(ns user
(:import (java.util.concurrent Executors)))
;; Thread factory for virtual threads
(defn thread-factory [name]
(-> (Thread/ofVirtual)
(.name name 0)
(.factory)))
;; Define an executor which just produce a new virtual thread for every task
(defonce unbounded-executor
(Executors/newThreadPerTaskExecutor (thread-factory "unbounded-pool-")))
(defmacro vfuture
"Takes a body of expressions and invoke the body in another virtual thread.
Returns ^java.util.concurrent.ThreadPerTaskExecutor$ThreadBoundFuture"
[& body]
`(.submit unbounded-executor (^{:once true} fn* [] ~@body)))
;; Run 10000 threads
(do
(dotimes [n 10000]
(.submit unbounded-executor ^Callable #(do
(Thread/sleep 10000)
(prn "Thread:" n))))
(println "done"))
;; Working with agents with virtual threads
(def a-counter (agent 0))
(send-via unbounded-executor a-counter inc)
(await a-counter)
@a-counter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment