Java中的多个对象锁? [英] Multiple object locks in Java?

查看:326
本文介绍了Java中的多个对象锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

锁定私有字段变量(而不是使用锁定对象)是安全/可接受的做法吗?这样,我可以有不同的锁定用于不同的目的。示例如下:

Is it safe/acceptable practice to lock on a private field variable (instead of using a lock object)? This way, I could have different locks for different purposes. Example below:

class Test {
  private Integer x = 0;
  private Integer y = 0;

  public void incrementX() {
    synchronized(x) {
      x++;
    }
  }

  public void decrementX() {
    synchronized(x) {
      x++;
    }
  }

  public void incrementY() {
    synchronized(y) {
      y++;
    }
  }

  public void decrementY() {
    synchronized(y) {
      y++;
    }
  }

或者我应该为每个私人成员我想锁定?示例:

Or should I have a lock object for each private member I wish to lock? Example:

class Test {
  private final Object xLock = new Object();
  private final Object yLock = new Object();
  private Integer x = 0;
  private Integer y = 0;

...

}

我应该只有一个单一的通用锁,并使用所有私人变量,需要锁定?示例:

Or should I just have a single general lock and use that for all private variables that require locking? Example:

class Test {
  private final Object objLock = new Object();
  private Integer x = 0;
  private Integer y = 0;

...

}


推荐答案

注意始终使用最终成员var 锁定!例如,如果你使用 Integer ,并且你打算更改它,这将是非常糟糕的做法,因为每个调用都会看到一个不同的对象并导致数据竞争。

Beware to always use a final member var for the lock! If you use an Integer, for example, and you plan to change it, that will be very bad practice since each call will see a different object and cause a data race.

是否使用一个或多个锁取决于您要实现的协调方案,因此它完全是特定于域的。你必须仔细思考哪些操作是哪些和哪些不是互斥的,并适当地分配锁。这里没有单一的最佳实践。

Whether you use one or several locks depends on the coordination scheme you want to achieve, so it's entirely domain-specific. You must think through carefully which operations are and which aren't mutually exclusive and assign locks to them appropriately. There is no single best practice here.

如果你有两个正交操作可能同时发生,而不会导致任何数据库,这是两个锁的情况。在你的例子中有两个整数,每个都独立地改变。我认为这是两个锁的情况。如果你有更复杂的代码,在至少一个操作中,你需要访问这两个整数,那将它们绑在一起,然后你将需要一个单一的锁。

If you have two orthogonal operations on your object that may happen simultaneously without causing any datarace, that's a case for two locks. In your example there are two Integers, each changing independently. I see this as a case for two locks. If you had more complex code where in at least one operation you needed to access both Integers, that would tie them together and then you would need a single lock.

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

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