Adding comments and refactoring further
This commit is contained in:
parent
6428f54e14
commit
d5d26c0445
@ -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;
|
||||
|
||||
// * * 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);
|
||||
|
||||
// * * 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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user