Today I was asked this interview question and could not answer.
If you have two instances of a Person class which has a setAddress method that is synchronized. Now if it was only one object and multiple threads were accessing it, the synchronized
will make sure that only one method can access it at a time.
But if there are different objects, one thread will not wait on the other before entering the method.
Now the question is…if I wanted to make the method synchronized across all instances of Person Objects, how do I do that?
Best Answer
Synchronize on the Person.class or create a static LOCK object on which you synchronize:
or
Either way, we're using a single (static) lock object instance which is common to all callers. Synchronizing on the class mirrors the default behavior of synchronized
static
methods. But it somewhat exposes the lock, which can be dangerous because for instance, some evil code could synchronize onPerson.class
and never release the lock, and make your code jam up. Keeping a separate private lock is therefore more secure.