class Test {
private int x=0;
private Object lockObject = new Object();
public void incBlock() {
synchronized(lockObject) {
x++;
}
System.out.println("x="+x);
}
public void incThis() { // same as synchronized method
synchronized(this) {
x++;
}
System.out.println("x="+x);
}
}
Personally I almost never lock on “this”. I usually lock on a privately held reference which I know that no other code is going to lock on. If you lock on “this” then any other code which knows about your object might choose to lock on it. While it’s unlikely to happen, it certainly could do - and could cause deadlocks, or just excessive locking.
There’s nothing particularly magical about what you lock on - you can think of it as a token, effectively. Anyone locking with the same token will be trying to acquire the same lock. Unless you want other code to be able to acquire the same lock, use a private variable. I’d also encourage you to make the variable final - I can’t remember a situation where I’ve ever wanted to change a lock variable over the lifetime of an object.
What is the difference between synchronized on lockObject and using this as the lock?
本文探讨了在Java中使用synchronized关键字的不同方式,特别是针对锁对象(lockObject)与当前对象(this)作为锁的区别。作者建议通常避免锁定当前对象,而是推荐使用私有引用变量,并解释了这种选择如何能更有效地避免死锁并减少不必要的锁定。
414





