Re: Lazy, cached supplier: most performant mutex mechanism?

Remi Forax via Concurrency-interest <[email protected]> Fri, 31 Jul 2020 19:58:26 +0200 (CEST)
Newsgroups gmane.comp.java.jsr.166-concurrency
Message-ID <[email protected]>
> De: "concurrency-interest" <[email protected]>
> À: "[email protected]"
> <[email protected]>
> Envoyé: Vendredi 31 Juillet 2020 19:40:21
> Objet: [concurrency-interest] Lazy, cached supplier: most performant mutex
> mechanism?

> This seems like it would be a common stdlib ask, but what is the most performant
> way to protect the code inside a supplier from being concurrently realized more
> than once? Contention would be rare, and the losing threads need to wait on the
> value being computed by the winning thread.

> The most straightforward thing to do is a synchronized block, but this currently
> pins a carrier thread in Project Loom.

> The Supplier needs to keep track of:
> 1) the thunk, if unrealized
> 2) a value, if realized

> Golang's sync.Once does this [1] (CAS, fallback to mutex. Doesn't remember
> value)
> Clojure's lazy sequences use synchronized [2]

> Is there a better way to approach this on the JVM?

For the JVM, you can use the class holder idiom, it uses the fact that class are lazily initialized in Java and that the static block are only run once. 
see [ https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom | https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom ] 

about your comment on synchronized block vs loom, you can use a RentrantLock instead which is loom-aware. 

> Thanks!

> [1] [ https://golang.org/src/sync/once.go | https://golang.org/src/sync/once.go
> ]
> [2] [
> https://github.com/clojure/clojure/blob/30a36cbe0ef936e57ddba238b7fa6d58ee1cbdce/src/jvm/clojure/lang/LazySeq.java#L39-L46
> |
> https://github.com/clojure/clojure/blob/30a36cbe0ef936e57ddba238b7fa6d58ee1cbdce/src/jvm/clojure/lang/LazySeq.java#L39-L46
> ]

cheers, 
Rémi

_______________________________________________
Concurrency-interest mailing list
[email protected]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest