In this blog post we will talk and learn about one of very important multi Threading Java interview question and question is that What do we understand by fair locks?
- A fair lock takes the waiting time of the threads into account when choosing the next thread that passes the barrier to some exclusive resource.
- An example implementation of a fair lock is provided by the Java is:java.util.concurrent.locks.ReentrantLock.
- If the constructor with the boolean flag set to true is used, the ReentrantLock grants access to the longest-waiting thread.
Let’s try to understand using an Example..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.kkjavatutorials.task; import java.util.concurrent.locks.Lock; public class MyTask { private Lock lock; public MyTask(Lock lock) { this.lock = lock; } public void task(){ lock.lock(); System.out.println("Task Started by Thread-"+Thread.currentThread().getName()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } System.out.println("Task Completed By Thread-"+Thread.currentThread().getName()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.kkjavatutorials.task; public class MyThread extends Thread { private MyTask myTask; public MyThread(MyTask myTask,String threadName) { super(threadName); this.myTask = myTask; } @Override public void run() { myTask.task(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.kkjavatutorials.client; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.kkjavatutorials.task.MyTask; import com.kkjavatutorials.task.MyThread; /** * @author KK JavaTutorials *What do we understand by fair locks? */ public class ClientTest { public static void main(String[] args) { System.out.println("Main Start.."); /** * The constructor for ReentrantLock class accepts an optional * fairness parameter. When set true under contention, locks * favor granting access to the longest-waiting thread. * Otherwise this lock does not guarantee any particular access order. */ Lock lock = new ReentrantLock(true); MyTask myTask = new MyTask(lock); MyThread myThread1 = new MyThread(myTask,"T-1"); MyThread myThread2 = new MyThread(myTask,"T-2"); MyThread myThread3 = new MyThread(myTask,"T-3"); myThread1.start(); myThread2.start(); myThread3.start(); System.out.println("Main End.."); } } |
Output
1 2 3 4 5 6 7 8 |
Main Start.. Main End.. Task Started by Thread-T-1 Task Completed By Thread-T-1 Task Started by Thread-T-3 Task Completed By Thread-T-3 Task Started by Thread-T-2 Task Completed By Thread-T-2 |
That’s all about What do we understand by fair locks?
If you have any feedback or suggestion please feel free to drop in blow comment box.