Skip to content

Instantly share code, notes, and snippets.

@damienstanton
Forked from mikeananev/virtual_threads.clj
Created June 20, 2023 12:38
Show Gist options
  • Save damienstanton/6e6b797ab09a91cd0171f57826dc485e to your computer and use it in GitHub Desktop.
Save damienstanton/6e6b797ab09a91cd0171f57826dc485e 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