I'm writing a computational library in scala. Similar functionality I group into native scala singleton objects containing bunch of procedures and some statically allocated memory for O(1) temporal data.
This approach is suited for a single-thread use. But calling library functions from different threads simultaneously may overwrite temporal data and give incorrect answers to callers.
I may just copy this library and write thread-safe version by moving all statically allocated memory inside functions local space. But I prefer to avoid it by defining thread-local variables.
Is it possible in scala?
Just use Java's java.lang.ThreadLocal
class to store the variables.
val tl = new ThreadLocal[String]
tl.set("fish")
tl.get // "fish"
Be aware that there is a nonzero performance penalty for doing this (~6 ns in my hands, as I recall). If you're doing really lightweight stuff (e.g. incrementing an index), you might notice the difference in speed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With