From d5d26c04452a0f996dd930221a6d44e7ff46bd0e Mon Sep 17 00:00:00 2001 From: hitanshu310 Date: Thu, 1 Jan 2026 12:12:37 +0530 Subject: [PATCH] Adding comments and refactoring further --- .../concurrency/DeadLockExampleWithLock.java | 54 ++++++++++++------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/hithomelabs/dsa/concurrency/DeadLockExampleWithLock.java b/src/main/java/com/hithomelabs/dsa/concurrency/DeadLockExampleWithLock.java index 44e8d27..6e4d75a 100644 --- a/src/main/java/com/hithomelabs/dsa/concurrency/DeadLockExampleWithLock.java +++ b/src/main/java/com/hithomelabs/dsa/concurrency/DeadLockExampleWithLock.java @@ -13,14 +13,22 @@ import java.util.concurrent.locks.ReentrantLock; class Paper{ private static Lock lock = new ReentrantLock(); - private String message; public String procurePaper() { - boolean hasLock = false; try{ if(lock.tryLock(500, TimeUnit.MILLISECONDS)){ - hasLock = true; - return "writing on paper ..."; + + // * * Inner try block if lock is acquired successfully + // * * To ensure the lock is always unlocked in the finally block + + try{ + return "writing on paper ..."; + } catch (Exception e) { + throw e; // * * Inner catch block just throws the exception for outer block to handle + } + finally { + lock.unlock(); + } } else{ return "Could not get lock"; @@ -28,10 +36,6 @@ class Paper{ }catch (Exception e){ System.out.println(e.getMessage()); } - finally { - if (hasLock) - lock.unlock(); - } return ""; } @@ -39,16 +43,31 @@ class Paper{ class Pen{ - private String message; private static Lock lock = new ReentrantLock(); public String procurePen(){ - boolean hasLock = false; + + // * * Outer try block, required because a tryLock with timeout needs to handle interrupts try{ if(lock.tryLock(500,TimeUnit.MILLISECONDS)){ - hasLock = true; - Thread.sleep(5000); - return "Writing with pen ..."; + + // * * Inner try block if lock is acquired successfully + // * * to ensure the lock is always unlocked in the finally block + + try { + + // * * After gaining lock, thread sleeps + // * * Causing the other thread to timeOut waiting to procurePen + + Thread.sleep(1000); + return "Writing with pen ..."; + } catch (InterruptedException e) { + throw e; + } + finally { + lock.unlock(); + } + } else{ return "Could not get lock"; @@ -57,13 +76,8 @@ class Pen{ catch(Exception e){ System.out.println(e.getMessage()); } - finally { - if(hasLock) - lock.unlock(); - } return ""; } - } @AllArgsConstructor @@ -74,8 +88,8 @@ class VendorWithLock1 implements Runnable{ @Override public void run() { - System.out.println(Thread.currentThread() + paper.procurePaper()); - System.out.println(Thread.currentThread() + pen.procurePen()); + System.out.println(Thread.currentThread() + ":" + paper.procurePaper()); + System.out.println(Thread.currentThread() + ":" + pen.procurePen()); } }