|
| 1 | +package multithreading.locks; |
| 2 | + |
| 3 | +import java.util.concurrent.locks.Lock; |
| 4 | +import java.util.concurrent.locks.ReentrantLock; |
| 5 | + |
| 6 | +public class ReentrantExample { |
| 7 | + private final Lock lock = new ReentrantLock(); |
| 8 | + |
| 9 | + public void outerMethod() { |
| 10 | + |
| 11 | + // 1. lock acquired by main thread |
| 12 | +// lock.lock(); // t1 ne lock le liya and innerMethod me ghus gya, and t2 wait krrha indefinitely for t1 to get finished, esko bolte hai BLOCKED/WAITING state, agar aap .lock() use krrhe to us waiting thread t2 ko interrupt nhi kr paynge |
| 13 | + try { |
| 14 | + lock.lockInterruptibly(); // lekin agar aapko usko interrupt krna hai, to lock ko interruptible hona bhi to chahie, to interruptexception throw hoga, to esko try/catch me krna pdega |
| 15 | + } catch (InterruptedException e) { |
| 16 | + throw new RuntimeException(e); |
| 17 | + } |
| 18 | + try { |
| 19 | + // 2. |
| 20 | + System.out.println("Outer method"); |
| 21 | + innerMethod(); |
| 22 | + } finally { |
| 23 | + lock.unlock(); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + public void innerMethod() { |
| 28 | + /* |
| 29 | + 3. jo lock phle se lock kr-rkha hai hmne usko fir se mai lock krne ka try krrha hu |
| 30 | + mai apna hi wait krrha hu - deadlock |
| 31 | +
|
| 32 | + But since the lock is Reentrant |
| 33 | + yani same thread holds it, to fir se whi thread acquire kr lega lock |
| 34 | +
|
| 35 | +
|
| 36 | + Jb hm Reentrant lock use krte hai to ek count maintain hota hai, ki lock kitni baar acquire kiya gya hai |
| 37 | + each lock call must be paired with an unlock call |
| 38 | + lock tb release hoga jb hr ek lock match ho jayega uske unlock se |
| 39 | + */ |
| 40 | + |
| 41 | + lock.lock(); |
| 42 | + try { |
| 43 | + System.out.println("Inner method"); |
| 44 | + } finally { |
| 45 | + lock.unlock(); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + public static void main(String[] args) { |
| 50 | + ReentrantExample example = new ReentrantExample(); |
| 51 | + example.outerMethod(); |
| 52 | + } |
| 53 | +} |
0 commit comments