Richard Hartman
Richard Hartman

Reputation: 1

Java Synchronized on object or variable?

Ok, I will try to phrase this clearly. Is the object synchronization on the object itself, or the reference to the object?

That is, if I have

Object lock1 = new Object();
Object lock2 = lock1;

will a block synchronized (lock1) block code synchronized (lock2)?

Both are referring to the same actual object, just with different references...

I think that it is the object that matters, not the reference, but I am not certain.

Thank you.

Upvotes: 0

Views: 108

Answers (1)

Object lock1 = new Object();
Object lock2 = lock1;

Both are referring to the same actual object, just with different references...

This is incorrect, the value of non-primitives in Java is the reference to the instance. Therefore, both are referring to the same Object with the same reference.

You can assign that Object to any variable you like and using a synchronized block will synchronize on that Object instance. The lock monitors are on Object instances themselves.

You can see a bit of evidence of that when take a look at the methods of the Object class related to locking. Here is the notify method used to notify threads that are waiting for the lock to be freed so they can execute the synchronized block:

https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#notify()

Upvotes: 1

Related Questions