我试图理解对象同步的概念。使用 Java Cert Book 中的这个示例,您能否帮助我理解以下两段代码之间的行为差异(一段代码我们在要保护其方法/操作免受竞争条件影响的对象上进行同步,另一段代码我们使用辅助对象作为锁来实现相同的目标):
1.
class Client {
BankAccount account;
public void updateTransaction() {
synchronized (account) {
account.update(); // update is safe because of lock on account obj
}
}
public double withdrawFunds() {
double amt;
synchronized (account) {
account.calculateInterest();
amt= account.withdraw();
}
return amt;
}
}
2.
class Client {
BankAccount account;
Object lock = new Object();
public void updateTransaction() {
synchronized (lock) {
account.update(); // update is safe because of a lock
}
}
public double withdrawFunds() {
double amt;
synchronized (lock) {
account.calculateInterest();
amt= account.withdraw();
}
return amt;
}
}
最佳答案
这两个都会抛出 NullPointerExceptions,但只是在不同的地方。
您应该始终在永远不会为 null(最终)的不可变引用上进行同步。
我想你的问题的答案是,对于给定的客户端,帐户可能会发生变化(假设有设置者),但锁定永远不会发生变化。同样,保证这一点的唯一方法是将其标记为最终的。
关于java - 了解Java中的同步块(synchronized block),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6444026/