Skip to content

Commit c1eb4e7

Browse files
committed
fairness of locks
1 parent eb6861f commit c1eb4e7

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package multithreading.locks;
2+
3+
import java.util.concurrent.locks.Lock;
4+
import java.util.concurrent.locks.ReentrantLock;
5+
6+
/*
7+
locking me fairness hoti hai, order determine hoti hai ki kon se thread ko lock milega, kyuki multiple thread wants lock,
8+
to sbse phle kisko milega fir kisko milega, to wo order jo hai usko fairness kehte
9+
10+
jo pehle aaya hai usko pehle lock milega
11+
12+
Fair Lock: Jo pehle aya, usko lock milega (FIFO)
13+
Unfair Lock: Jo fast hai wo ghus jata hai, chahe baad me aaya ho
14+
15+
let's say 20 threads hai and unme se ek to lock mil hi nhi rha hai baaki sb race krrhe hai, (starvation)
16+
this doesn't happen in fairness, mauka sbko milega, order to FIFO rhega hi but mauka sbko milega
17+
18+
Disadvantages of synchronization:
19+
- synchronized me fairness ki guarantee nhi hai
20+
- indefinitely blocking hoti hai
21+
- interruptibility bhi nhi hai
22+
- synchronized ko pta hi nhi hai kon sa read / write hai to wo to poora block krke rkhega
23+
*/
24+
25+
public class FairnessLockExample {
26+
// private final Lock unfairLock = new ReentrantLock();
27+
private final Lock lock = new ReentrantLock(true);
28+
29+
public void accessResource() {
30+
lock.lock();
31+
try {
32+
System.out.println(Thread.currentThread().getName() + " acquired the lock");
33+
Thread.sleep(1000);
34+
} catch(InterruptedException e) {
35+
Thread.currentThread().interrupt();
36+
} finally {
37+
System.out.println(Thread.currentThread().getName() + " released the lock");
38+
lock.unlock();
39+
}
40+
}
41+
42+
public static void main(String[] args) {
43+
FairnessLockExample example = new FairnessLockExample();
44+
45+
Runnable task = new Runnable() {
46+
@Override
47+
public void run() {
48+
example.accessResource();
49+
}
50+
};
51+
52+
Thread thread1 = new Thread(task, "Thread 1");
53+
Thread thread2 = new Thread(task, "Thread 2");
54+
Thread thread3 = new Thread(task, "Thread 3");
55+
56+
thread1.start();
57+
thread2.start();
58+
thread3.start();
59+
}
60+
}

0 commit comments

Comments
 (0)