making thread-local objects on scala

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.


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.