What object do I synchronize on in Scala?

后端 未结 3 2270
情歌与酒
情歌与酒 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:36

    If the premise is that you want to avoid locking on this because another thread with third party code can lock on the same object, then Scala offers one more level of visibility private[this].

    class C {
      private[this] val lock = new Object()
      def method1(): Unit = lock.synchronized {
        println("method1")
      }
    }
    

    Here actually no other object other than a particular instance of C can access lock. Even other instances from the same class cannot access lock.

提交回复
热议问题