java synchronized multiple - What object do I synchronize on in Scala?

1 Answers

In Scala it's even more straightforward to get the same behavior (I'm assuming you want to lock on the contained object for some reason e.g. more fine-grained control than locking the whole instance of that class):

class Class1 {
  private object Locker
  def method1 { Locker.synchronized { ... } }

But you should rarely control things this way. In particular, it won't prevent deadlocks in either C# or Scala without a lot of attention to what goes into ....

You should at least use the concurrency tools in java.util.concurrent, and you may want to look into futures or actors.

objects synchronized(this) vs

In C# it's pretty straightforward:

class Class1{
  private static readonly object locker = new object();
  void Method1(){
    lock(locker) { .... }

And I definitely should not make a synchronization on this because it might lead to a deadlock. Likewise, in Scala I saw examples and couldn't get the idea of what is the basic principle of synchronization and object (field) I should use to make a synchronization:

def add(user: User) {
  // tokenizeName was measured to be the most expensive operation.
  val tokens = tokenizeName(

  tokens.foreach { term =>
    userMap.synchronized {
      add(term, user)

class Person(var name: String) {
  def set(changedName: String) {
    this.synchronized {
      name = changedName

#3 and so on...

Would you mind making it clear for me?