What object do I synchronize on in Scala?

后端 未结 3 2271
情歌与酒
情歌与酒 2021-02-19 02:58

In C# it\'s pretty straightforward:

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


        
3条回答
  •  粉色の甜心
    2021-02-19 03:38

    1. Having a lock on object in Scala is the same as having the lock on static field/class in Java, which is basically one of 'hardest' locks. It will block operations not on instance of class, but on class itself in scope of class loader. You should think carefully when introducing locks like this. It doesn't protect you from a deadlock due to incorrect ordering of acquired locks, but instead leads to blocking threads if ones are working with different instances of a class, and may not interfere at all.

    2. having a lock on 'this' or some class (not object) field (mutex) is more relaxed way of synchronization, you should use it for managing access not to class - but to particular instance of this class.

    3. look at actors in akka, they rock and eliminate many of problems with synchronization.

    side-note: making synchronization on 'this' doesn't imply deadlocks.

提交回复
热议问题