Skip to content

Commit

Permalink
io-thread with dynamic vthread use through the runtime ExecutorService
Browse files Browse the repository at this point in the history
  • Loading branch information
fogus committed Jan 16, 2025
1 parent 313569a commit 86f8365
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions src/main/clojure/clojure/core/async.clj
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@ to catch and handle."
)
(:import [java.util.concurrent.atomic AtomicLong]
[java.util.concurrent.locks Lock]
[java.util.concurrent Executors Executor ThreadLocalRandom]
[java.util.concurrent Executors Executor ThreadLocalRandom ExecutorService]
[java.util Arrays ArrayList]
[clojure.lang Var]))
[clojure.lang Var]
[java.lang Thread$Builder]))

(alias 'core 'clojure.core)

Expand Down Expand Up @@ -465,6 +466,37 @@ to catch and handle."
(defonce ^:private ^Executor thread-macro-executor
(Executors/newCachedThreadPool (conc/counted-thread-factory "async-thread-macro-%d" true)))

(def ^ExecutorService io-thread-exec
(if (= "21" (System/getProperty "java.vm.specification.version"))
(eval '(Executors/newThreadPerTaskExecutor (-> (Thread/ofVirtual)
(Thread$Builder/.name "io-thread-" 0)
.factory)))
thread-macro-executor))

(defmacro io-thread
"Asynchronously executes the body in a virtual thread, returning immediately
to the calling thread.
io-thread blocks should not (either directly or indirectly) perform operations
that may block indefinitely. Doing so risks pinning the virtual thread
to its carrier thread.
Returns a channel which will receive the result of the body when
completed"
[& body]
`(let [c# (chan 1)
captured-bindings# (Var/getThreadBindingFrame)]
(.execute
io-thread-exec
(^:once fn* []
(Var/resetThreadBindingFrame captured-bindings#)
(try
(let [result# (do ~@body)]
(>!! c# result#))
(finally
(close! c#)))))
c#))

(defn thread-call
"Executes f in another thread, returning immediately to the calling
thread. Returns a channel which will receive the result of calling
Expand Down

0 comments on commit 86f8365

Please sign in to comment.