4

Suppose there are 2 classes, Parent class and Child class which extends Parent class. Now and both have two method which are synchronized.My question which object lock will be use for locking this synchronized methods i create object like : Parent p=new Child(); Is is parent object lock or Child object lock?

1
  • 1
    For a synchronized instance method, it's always the receiver object's intrinsic lock. The reference type doesn't matter. Commented Jul 12, 2014 at 8:00

3 Answers 3

5

There is no parent object lock or child object lock. There is only one lock, the object's. In this case, it will be p's.

Threads will block when entering a parent's synchronized method if another thread has the lock in a child's synchronized method, and vice versa.

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

Comments

2

There aren't separate parent and child locks. The object only has one lock. Whatever the inheritance hierarchy looks like, all synchronized methods of the object and all synchronized blocks synchronized on the object use the same lock.

Comments

1

I think the reason people get confused here is that: class inheritance inherits instance fields. But for methods, it will just inherits methods implementation. So there is only lock being used, which is p in your case. Let me know if it makes sense.

Also it is not a good idea to use inheritance for additional locking. Use composition - decorator pattern. See JCIP Chapter 4.4.1

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.