Multithreading – creating threaded local objects on Scala

I'm writing a computing library in scala Similar functions I grouped into local Scala singleton objects containing some programs and some statically allocated memory for O (1) time data

This method is suitable for single thread However, calling library functions from different threads at the same time may overwrite the time data and provide incorrect answers to the caller

I can copy this library and write a thread safe version by moving all statically allocated memory in the function local space But I prefer to avoid it by defining thread local variables

Is it possible in scala?

Solution

Just use Java Lang. ThreadLocal class to store variables

val tl = new ThreadLocal[String]
tl.set("fish")
tl.get   // "fish"

Please note that doing so will result in non-zero performance loss (I remember about 6 ns in my hands) If you're doing something really lightweight (such as incremental indexing), you may notice speed differences

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>