I'm reading J.Bloch's effetive Java and now I'm at the section about documenting thread-safety. He provides an example using locks:
private final Object lock = new Object();
public void foo(){
synchronized(lock){
...
}
}
and said this:
Note that the
lock
field is declaredfinal
. This prevents you from inadvertently changing its contents, which could result in catastrophic unsynchronized access to the containing object.
Should we adhere to the rule always declaring lock object final? From the first glance, I could see that if the one thread modify the lock
within the synchronized block and some other try to acquire the monitor of the modified object (which is free) right after the modifying. But it appears to me as a "theoretical problem" hardly reproducing in practice. Maybe I miss something?