These following questions are on synchronized methods. I've included my guess.
Anyone finding these wrong or willing to add anything to these
are most welcome. I really need help on these. I look for experts on these.
Q1. What happens to a thread that fails to grab a monitor for a specific object? I think:
-------
This thread will look for another schedule i.e. it will be at the mercy of thread scheduler.
Q2. How an InterruptedException is thrown? I think:
-------
Consider following situation :
Reference oD has 3 methods; mAA, mBB are synchronized, mCC is not.
mAA, mBB, mCC all modify oD.
3 threads tA, tB, tC all operate on oD.
tA calls mAA, tB calls mBB, tC calls mCC.
Now,
(1) As these threads are scheduled, let's say,tA is running first.
tA grabs the monitor on oD, calls mAA and is now working.
(2) Now the scheduler runs tB. As tB tries to grab monitor on oD, it
sees monitor is busy and looks for next schedule.
(3) Now tC gets to run. It calls mCC, mCC tries to modify oD. Now
InterruptedException is thrown.
Q3. When a thread calls 'sleep()' or 'wait()' or 'yield()' in synchronized methods, is the monitor is released? I think:
-------
According to a Mughal example (9.3), 'wait()' releases monitor.
A wild guess is,
as a method calling 'wait()' must be notified by other threads, it should
release monitor.
I don't know about 'sleep()'.
But one thing I cannot understand is that,
'sleep()' and 'wait()' throw InterruptedException. If 'wait()' releases
the monitor, how and when this exception is thrown.
Q4. Related to Q3, join( , ) method is marked as synchronized
but join() is not. Both of them throw InterruptedException.
Why these two are different? How the exceptions are thrown?