我有以下仅包含一个字段的类i
。对该字段的访问由对象的锁(“this”)保护。在实现 equals() 时,我需要锁定这个实例 (a) 和另一个 (b)。如果线程 1 调用 a.equals(b),同时线程 2 调用 b.equals(a),则两种实现中的锁定顺序是相反的,可能会导致死锁。
我应该如何为具有同步字段的类实现 equals()?
public class Sync {
// @GuardedBy("this")
private int i = 0;
public synchronized int getI() {return i;}
public synchronized void setI(int i) {this.i = i;}
public int hashCode() {
final int prime = 31;
int result = 1;
synchronized (this) {
result = prime * result + i;
}
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Sync other = (Sync) obj;
synchronized (this) {
synchronized (other) {
// May deadlock if "other" calls
// equals() on "this" at the same
// time
if (i != other.i)
return false;
}
}
return true;
}
}