Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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
1  
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
add comment

1 Answer

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

synchronize(Person.class){
    //...
}

or

private static final Object LOCK = new Object();

//...
synchronize(LOCK){
    //...
}
share|improve this answer
1  
Explain why that works. –  Robert Harvey Jul 31 '13 at 22:56
1  
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
add comment

Your Answer

 
discard

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.