Using synchronized/locks in future code

akka, concurrency, java, playframework-2.0, scala

Solution

This is an old question)) see here using-actors-instead-of-synchronized for example. In short it would be more advisable to use actors instead of locks:

class GreetingActor extends Actor with ActorLogging {

  def receive = {
    case Greeting(who) ⇒ log.info("Hello " + who) 
  }
}

only one message will be processed at any given time, so you can put any not-thread safe code you want instead of log.info, everything will work OK. BTW using ask pattern you can seamlessly integrate your actors into existing code that requires futures.

Problem

We are building a web app with Scala, Play framework, and MongoDB (with ReactiveMongo as our driver). The application architecture is non-blocking end to end. In some parts of our code, we need to access some non-thread-safe libraries such as Scala's parser combinators, Scala's reflection etc. We are currently enclosing such calls in `synchronized` blocks. I have two questions: - Are there any gotchas to look out for when using `synchronized` with future-y code? - Is it better to use locks (such as `ReentrantLock`) rather than `synchronized`, from both performance and usability standpoint?

Original source

Related problems