Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Today I was asked this interview question and could not answer. : If you have two instances of a Person Object and each of them have a setAddres method that is synchronized. Now if it was only one object and multiple threads were accessing it, the nsynchronized 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 to do that?

share|improve this question
Sounds like a trick question, or I'm misunderstanding what you're saying, or you're not explaining it right. If it's an instance method, then it doesn't matter if there are other instances of that object unless the instance(s) access some shared, mutable, state. – Steve Evers Jul 31 '13 at 22:15

you synchronize on the Person.class or create a static LOCK object on which you synchronize:



private static final Object LOCK = new Object();

share|improve this answer
Explain why that works. – Robert Harvey Jul 31 '13 at 22:56
Locking on a private static field is MUCH safer than locking the class itself. Locking the class breaks encapsulation and gives up control of the lock to anything can see the class. – Despertar Jul 31 '13 at 23:00
@Despertar Interesting then that the class is used for synchronizing static methods - e.g. see this answer – Steve Chambers Sep 14 '15 at 10:53

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.