-
-
Save damienstanton/6e6b797ab09a91cd0171f57826dc485e to your computer and use it in GitHub Desktop.
Java 19 virtual threads and Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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