Adding comments and refactoring further

This commit is contained in:
hitanshu310 2026-01-01 12:12:37 +05:30
parent 6428f54e14
commit d5d26c0445

View File

@ -13,14 +13,22 @@ import java.util.concurrent.locks.ReentrantLock;
class Paper{ class Paper{
private static Lock lock = new ReentrantLock(); private static Lock lock = new ReentrantLock();
private String message;
public String procurePaper() { public String procurePaper() {
boolean hasLock = false;
try{ try{
if(lock.tryLock(500, TimeUnit.MILLISECONDS)){ if(lock.tryLock(500, TimeUnit.MILLISECONDS)){
hasLock = true;
// * * Inner try block if lock is acquired successfully
// * * To ensure the lock is always unlocked in the finally block
try{
return "writing on paper ..."; 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{ else{
return "Could not get lock"; return "Could not get lock";
@ -28,10 +36,6 @@ class Paper{
}catch (Exception e){ }catch (Exception e){
System.out.println(e.getMessage()); System.out.println(e.getMessage());
} }
finally {
if (hasLock)
lock.unlock();
}
return ""; return "";
} }
@ -39,16 +43,31 @@ class Paper{
class Pen{ class Pen{
private String message;
private static Lock lock = new ReentrantLock(); private static Lock lock = new ReentrantLock();
public String procurePen(){ public String procurePen(){
boolean hasLock = false;
// * * Outer try block, required because a tryLock with timeout needs to handle interrupts
try{ try{
if(lock.tryLock(500,TimeUnit.MILLISECONDS)){ if(lock.tryLock(500,TimeUnit.MILLISECONDS)){
hasLock = true;
Thread.sleep(5000); // * * 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 ..."; return "Writing with pen ...";
} catch (InterruptedException e) {
throw e;
}
finally {
lock.unlock();
}
} }
else{ else{
return "Could not get lock"; return "Could not get lock";
@ -57,13 +76,8 @@ class Pen{
catch(Exception e){ catch(Exception e){
System.out.println(e.getMessage()); System.out.println(e.getMessage());
} }
finally {
if(hasLock)
lock.unlock();
}
return ""; return "";
} }
} }
@AllArgsConstructor @AllArgsConstructor
@ -74,8 +88,8 @@ class VendorWithLock1 implements Runnable{
@Override @Override
public void run() { public void run() {
System.out.println(Thread.currentThread() + paper.procurePaper()); System.out.println(Thread.currentThread() + ":" + paper.procurePaper());
System.out.println(Thread.currentThread() + pen.procurePen()); System.out.println(Thread.currentThread() + ":" + pen.procurePen());
} }
} }