Multiple object locks in Java?

Is it safe / acceptable to lock private field variables instead of using locked objects? In this way, I can have different locks for different purposes Examples are as follows:

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 locked object for each private member I want 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 have only one universal lock and use it for all private variables that need to be locked? Example:

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

...

}

Solution

Note that the end member VaR is always used for locking! For example, if you use integer and plan to change it, it will be very bad practice, because each call will see different objects and cause data contention

Whether you use one or more locks depends on the coordination scheme you want to implement, so it is completely domain specific You must carefully consider which operations are and which are not mutually exclusive, and assign locks to them appropriately There is no single best practice

If there are two orthogonal operations on your object that may occur at the same time without causing any datarace, then there are two locks In your example, there are two integers, each changed independently I think this is the case of two locks If you have more complex code, you need to access two integers in at least one operation, tie them together, and then you need a lock

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>