In the code given below. How can I know which object Reentrant Lock has locked ?
Public class Test {
Map obj1 = new HashMap();
Object ob2 = new Object();
void Method() {
//First
synchronized(ob1) { // Locks obj1
}
synchronized(ob2) { // Locks obj2
}
//Second
Lock lock = new ReentrantLock(); // Which object is getting locked here?
lock.lock();
try {
} finally {
lock.unlock();
}
}
}
In the above example which Object is getting locked ? If I want to explicitly lock obj1 and obj2 using Reentrant lock how is it possible ?
The
lock
object is getting locked there.I think maybe you misunderstand what
synchronized(ob1) {...}
does. It does not prevent other threads from usingobj1
. The only thing it prevents is, it prevents other threads from being synchronized on the same object at the same time.Locks in Java (and in most other programming languages/libraries) are so-called advisory locks. "Advisory" means, the programmer has to know what data are supposed to be protected by the lock, and the programmer is responsible for ensuring that no thread in the program ever uses that data except when the thread has locked the lock.
FYI: A "clean" practice in Java is to use
synchronized
in this way:This pattern allows you to publish instances of
MyClass
without exposing thelock
object to callers. It also makes very clear the distinction between thelock
object itself, and the data/relationships that are protected by the lock.The pattern also makes it trivially easy to switch from using
synchronized
to using aLock
object if you need to do so in the future.