Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making thread-local objects on scala

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?

like image 974
ayvango Avatar asked Jan 05 '13 20:01

ayvango


1 Answers

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.

like image 126
Rex Kerr Avatar answered Sep 24 '22 16:09

Rex Kerr