Hi Everyone,
After coding up the locking section of the Data.class using synchronized methods and wait()/notify() calls for handling threads which are tying to lock on records already locked by other threads; I realized that technically the notify() call can wake up a
thread wanting to lock on a different record. Better explained
here
Oricio Ocle wrote:Ok think about that:
If the specified record is already locked by a different
client, the current thread gives up the CPU and consumes no CPU cycles until the record is unlocked.
.... But it's record has not been unlocked ...
Regards
So, I've now used ReentrantLocks similar to what Simon suggests
here:
Simon Cockayne wrote:Hi Liviu,
Have a HashMap recordLocks: mapping key is wrapped a recNo. Mapping value is a RecordLock object.
A RecordLock class extends ReentrantLock and has a reference to the recordLock owner and a reference to a unique condition.
Ergo, any thread that wants to wait on the recordlock (so it can update the owner informaiton) can call theCondition.await().
And any thread that has finished with a recordLock (having unlocked it say) can call theCondition.signal().
This works fine but I'm struggling with removing the entries from the Map<RecNo, RecordLock>, where RecordLock just contains a ReentrantLock with a concurrent.locks.Condition to group the specific threads that wish to be woken up as the unlock of a specific record occurs to meat the criteria "the current thread gives up the CPU and consumes no CPU cycles until the
record is unlocked."
I've been looking at WeakHashMaps and the ReentrantLock methods such as getHoldCount() or hasQueuedThreads() but it just seems difficult to safely remove the entries (and ensure no othre thread is waiting/using the ReentrantLock object). Of course, I could just leave them in the Map<,> and explain it doesn't take up much memory at all. Or I wonder if someone is going to answer that the original wait()/notify() is good enough and that if one just writes about it in their choices.txt that's it's easier for a junior programmer perhaps Oracle might let you off or just deduct a few points at worst ...
Many Thanks