Make delicious recipes!


To ensure fairness to every thread so that it does not starve, we can implement our own Lock. Consider the below code:

Advantage of the above Lock object is that it allows conditional unlocking and the lock can be passed along in functions so that unlocking can be done in some function other than the locking function. This helps us achieve more locking flexibility than the plain synchronized method/block.

Basically it lets you treat Lock as an object and use it programmatically.

The above Lock object does not ensure fairness since notify leaves the task of waking up a thread on the system. Hence this class also does not ensure fairness.

To achieve fairness, the Lock class can have a queue of Objects - one object on which each thread waits exclusively. Using this queue, unlock can ensure fairness by processing the threads in a cyclic fashion thus making sure that no thread starves for its turn.

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Email: (Your email is not shared with anybody)

Facebook comments:

Site Owner: Sachin Goyal