I’m relatively new to concurrency in Java (still have yet to read JCIP, but it’s on my list!) and I have a question regarding locking behavior. Specifically, does Java lock on the reference of an object, or on the object itself?
Code example (not an sscce because I don’t know how to demo this behavior in practice):
static final Object lockA = new Object();
public void method1() {
synchronized(lockA) {
// do stuff here
}
}
public void method2() {
Object lockB = lockA;
synchronized(lockB) {
// do stuff
}
}
If another thread is executing method1() (and therefore has a lock on lockA), will method2() be allowed to execute?
Thanks!
Synchronization is done on the object, so the synchronized block in
method2will need to wait for the synchronized block inmethod1to finish.Each object has an “intrinsic lock” associated with it (see Intrinsic Locks and Synchronization). The synchronized block uses the intrinsic lock associated with the object on which you are synchronizing.