I’ve come across code like the following several times
class Foo {
private Object lock = new Object();
public void doSomething() {
synchronized(lock) {
...
What I’m interested in is why a lock object is created instead of writing synchronized(this)? Is it there to enable sharing the lock? I vaguely remember reading that it is an optimization. Is that true? Also, does it, in some context, make sense to have the lock declared as final?
thisis discouraged because if the object itself is used as a lock from the outside it would break the internal synchronization. Also, remember thatsynchronizedmethods are also usingthisas a lock, which may cause an unwanted effect.finalis recommended to prevent a situation in which a lock object is reassigned inside asynchronizedblock, thus causing different threads to see different lock objects. See this other question: Locking on a mutable object – Why is it considered a bad practice?