What object do I synchronize on in Scala?

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

    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.

提交回复
热议问题