'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?



Solution 1:[1]

Since Java 8 release, there is a more declarative way to initialize ThreadLocal:

Scala:

val local = ThreadLocal.withInitial[String](() => "init value");

Analogue in Java:

ThreadLocal<String> local = ThreadLocal.withInitial(() -> "init value");

Until Java 8 release you had to do the following:

Scala:

val local = new ThreadLocal[String]{
  override def initialValue = "init value"
}

Analogue in Java:

ThreadLocal<String> local = new ThreadLocal<String>(){
    @Override
    protected String initialValue() {
        return "init value";
    }
};

Note: Evaluation is lazy since you are passing java.util.function.Supplier lambda that is evaluated only once when ThreadLocal#get is called but value was not previously evaluated.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1