I want a thread-safe (immutable) Scala class for a long working task. For some corner cases the tasks takes very long so I want to implement a time-out. What’s the best way to implement this in an immutable class?
My first attempt was to use an implicit parameter like this:
class Worker(val input: String) {
def start: String = {
implicit val startTimeStamp = new TimeStamp
doSomething1 + doSomething2
}
def doSomething1()(implicit startTimeStamp: TimeStamp): String = { ... }
def doSomething2()(implicit startTimeStamp: TimeStamp): String = {
...
checkTimeout
...
}
}
class TimeStamp { val start = System.currentTimeMillis }
This should work, but there is still a lot of boiler-plate code with the implicit parameters. (In the real code I have hundreds deeply nested doSomething-functions in the worker class.) Is there a more beautiful way to do this in Scala?
Sounds like you are looking for futures. In scala 2.9.x I would suggest you to use the akka library for that, from 2.10.0 on there is the
scala.concurrent.Futuretrait.example for 2.10:
edit: added
blockingcall as suggested by Viktor Klang.