ThreadLocal Singleton with Scalas Option[T]

Javas ThreadLocal<T> class returns null if the thread local value is unset for the Thread. But this can be a valid value as well. Scala is more precisely and provides a representation for a non-existent value:

None extends Option[Nothing]

In my case I have overwritten the inititalValue method of ThreadLocal and used the ScalaThreadLocal with a match statement:

class ScalaThreadLocal[T] extends ThreadLocal[Option[T]] {
  override protected def initialValue: Option[T] = None
}

object CouchDBAccess {
  private val s = new ScalaThreadLocal[CouchDBAccess]()

  def apply() = s get match {
    case Some(x) => x
    case None => s set Option(new CouchDBAccess) ; s.get.get
  }
}

CouchDBAccess is the companion object of class CouchDBAccess.

I can simply use it like this:

abstract class ServiceBase {
  def dba = CouchDBAccess()
}

Comments are closed.