我在Scala中同步什么对象? [英] What object do I synchronize on in Scala?

查看:157
本文介绍了我在Scala中同步什么对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中它非常简单:

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

我绝对不应该在这个上进行同步,因为它可能会导致死锁。同样,在Scala中我看到了一些示例,无法了解同步和对象(字段)的基本原理是什么,我应该用它来进行同步:

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:

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

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

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

#3 and so on...

你介意说清楚吗?我?

推荐答案


  1. 锁定对象 Scala与在Java中对静态字段/类进行锁定相同,这基本上是最难的锁之一。它将阻止不在类实例上的操作,而是在类加载器范围内的类本身上。在引入这样的锁时你应该仔细考虑。它不能保护您免受由于获取的锁的错误排序而导致的死锁,而是会导致阻塞线程,如果它们正在处理类的不同实例,并且可能根本不会干扰。

  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.

锁定'this'或某些类(非对象)字段(mutex)是更轻松的同步方式,你应该用它来管理不要访问类的访问 - 而是用于特定的实例这个班。

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.

看看 akka 中的演员,他们摇滚并消除了许多同步问题。

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

side-note :在'this'上进行同步这意味着死锁。

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

这篇关于我在Scala中同步什么对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆