question on object lock
Hi,
I am reading the book "Java Threads". When synchronize a block of code must be carefull to lock the physical object, not the reference to object (page 56). I don't understand "physical object", in java do we use variables as reference? Besides use "synchronized(this)" what else can I use? Thanks
[314 byte] By [
jennyhua] at [2007-11-26 16:51:46]

# 2
"be careful to lock the physical object, not the reference," is kind of misleading and meaningless.
A lock is always associated with an object, not with a refrence. What they might be trying to say i that you hvae to be careful to understand that point. Here's what might happen if you think the lock is associated with the reference (or the variable).
Foo foo = new Foo();
synchronized(foo) {
foo = new Foo();
// You might think you have a lock on the "foo" variable, and therefore
// on the new Foo object, but you don't. The lock you hold is still on the
// original Foo object
}
# 3
Similarly,
Object o1 = new Object();
Object o2 = o1;
synchronized(o1) {
//...
}
synchronized(o2) {
//...
}
These two sync blocks are locking the same object, even though they access it through different references.