This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Can any one explain this with example: Threads calling non-static synchronized methods in the same class will only block each other if they're invoked using the same instance. That's because they each lock on this instance, and if they're called using two different instances, they get two locks, which do not interfere with each other.
SCJP1.5(81%), SCDJWS(94%), next mission SCEA (but need to wait or that)
When ever a thread encounters any synchronized method, it would acquire the lock on the object to complete through that synchronized method. Meanwhile, if any other concurrent thread also encounters the same method, it would also request for the lock, but is not granted until lock on that object is free. Once the first thread comes out of the synchronized method, it releases the lock and any other waiting thread would acquire it. This is the normal locking mechanism. Now coming to our quesion, two threads working on same object, would block each other if they encounter a synchronized method. Since there is only one object and each object can have only one lock, this is a true scenario. Also to remember here, even though the two treads are not invoking the same synchronized method, but still they would block each other, if they encounter two different synchronized methods of the same object at the same time.
Now coming to the second question, if the two threads are acting on two instances, then obviously the two objects would have their own locks and certainly there is no race condition for the two threads as both acquire locks one on each object.
In the first code I have passed two different instances of the same class and initiated two threads. here i got the output
In the second code i passed same instance and initated two threads and i got the output
I think we see this beacause in the first case when the thread with the name Paddy goes to sleep inside the synchornized block it was holding a different instance (tt1)than the thread Iyer (tt2). So Iyer never stopped executing and completed before the thread Paddy completed. In the second code both threads hold same instance tt1. So it blocked the iyer thread also from executing.
I think this is the answer if i am wrong please correct me.