Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Wednesday, December 5, 2012

Why nonfair lock is faster than fair lock (java.util.concurrent.locks.Lock) in Java Concurrency


This is the nonfair scenario:
When a thread B asks to hold a lock, if the lock is already taken by another thread A. Then the thread B will be suspended. After thread A finished his job, it releases the lock, then thread B is resumed. However, B needs a period of time to be able to actually run it's task from where it was suspended. And this period of time could be relatively long compared to another thread C who is asking for that exact same lock at the same time. If C could acquire the lock, does C's job and release the lock before B even "wakes up" (the time between B's resumed and B's able to actually run), then it's a win-win situation for B and C. Because C gets the lock and has it's job done and releases the lock, while B's "waking up" and B gets the lock no later than it otherwise would have.

In the fair scenario:
The C will be queued after B.

To set the fairness of a Lock, one can use the parametered constructor:
Lock lock = new ReentrantLock(true); //true for fair, false for nonfair