Skip to content

Instantly share code, notes, and snippets.

@4mitch
Created December 25, 2019 21:38
Show Gist options
  • Save 4mitch/dda69480260ef4feb4d5e505da9dad24 to your computer and use it in GitHub Desktop.
Save 4mitch/dda69480260ef4feb4d5e505da9dad24 to your computer and use it in GitHub Desktop.
JDK 14 - Project Loom virtual threads (ex-fibers) test - CAS vs LongAdder performance comparison
(ns me.core
(:import [java.util.concurrent.atomic LongAdder]
[java.util.concurrent CountDownLatch]))
(defmacro fiber [& body]
`(.. (Thread/builder)
(virtual)
(task (fn [] ~@body))
; (build)
(start)))
(time
(let [c (atom 0)
n (int 1e8)]
(dotimes [_ n]
(swap! c inc))
@c))
;; thread contention - ~10 times slower than 1 thread
(time
(let [s (atom 0)
n (int 100)
doneSignal (CountDownLatch. n)]
(dotimes [_ n]
(fiber
(dotimes [_ 1e6] (swap! s inc))
(.countDown doneSignal)))
(.await doneSignal)
@s))
(time
(let [a (LongAdder.)
n (long 1e8)]
(dotimes [_ n]
(.increment a))
(.sum a)))
;; non-blocking LongAdder - nice! - ~6 times faster on 4 cores than 1 thread
(let [a (LongAdder.)
n-threads (int 1000)
startSignal (CountDownLatch. 1)
doneSignal (CountDownLatch. n-threads)]
(dotimes [_ n-threads]
(let [t (fiber (do
(.await startSignal)
(dotimes [_ 100000] (.increment a))
(.countDown doneSignal)))]
t))
(time (do
(.countDown startSignal)
(.await doneSignal)
(.sum a))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment