2

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!

2 Answers 2

6

Synchronization is done on the object, so the synchronized block in method2 will need to wait for the synchronized block in method1 to 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.

Sign up to request clarification or add additional context in comments.

Comments

3

No, method2() will block since the two methods are synchronizing on the same object (lockB is merely a reference pointing to the same object as lockA).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.