3

I understand that static synchronized lock on Class objects, and non static locks on Object instance.

However in the accepted answer for this question: Static versus non-static lock object in synchronized block

When you use a non-static lock object:

  • thread 1 calls o1.foo()
  • thread 2 calls o1.foo(), will have to wait for thread 1 to finish
  • thread 3 calls o2.foo(), it can just continue, not minding thread 1 and 2

Why can Thread 3 just continue without regarding thread 1 and 2. Shouldnt Thread 3 have to wait to acquire the lock on the Object instance 'this' from either thread 1 or 2 before it can proceed ?

Community
  • 1
  • 1
Shivam Sinha
  • 4,924
  • 7
  • 43
  • 65
  • 1
    Can you specify your question more? Because the question you asked is answered in the link you provided - they are different Object instances, so thread 3 is locking on another lock from thread 1 and 2. – Nier Mar 20 '16 at 06:46
  • Yes my bad I thought they were the same instance hence the confusion. – Shivam Sinha Mar 20 '16 at 06:51

1 Answers1

2

Why can Thread 3 just continue without regarding thread 1 and 2.

Because it is locking a different object.

(Unless o1 and o2 happen to refer to the same object ....)

Shouldnt Thread 3 have to wait to acquire the lock on the Object instance 'this' from either thread 1 or 2 before it can proceed ?

Nope. The calls attempt to synchonize on (i.e. lock) o1 and o2 respectively. These will become the this for the respective threads when the foo() method calls start. The this of the respective threads while in the calling context(s) is not relevant.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216