Skip to content

Instantly share code, notes, and snippets.

@mahadevshindhe
Created November 9, 2021 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahadevshindhe/fe4022702ce821397e90da4313cde4ad to your computer and use it in GitHub Desktop.
Save mahadevshindhe/fe4022702ce821397e90da4313cde4ad to your computer and use it in GitHub Desktop.
Java Custom Re Entrant Lock implmentation
public class CustomRentrantLock {
public static void main(String[] args) {
LockCustom LockCustom=new ReentrantLockCustom();
MyRunnable myRunnable=new MyRunnable(LockCustom);
new Thread(myRunnable,"Thread-1").start();
new Thread(myRunnable,"Thread-2").start();
}
}
class MyRunnable implements Runnable{
LockCustom lockCustom;
public MyRunnable(LockCustom LockCustom) {
this.lockCustom=LockCustom;
}
public void run(){
System.out.println(Thread.currentThread().getName() +" is Waiting to acquire LockCustom");
lockCustom.lock();
System.out.println(Thread.currentThread().getName() +" has acquired LockCustom.");
try {
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() +" is sleeping.");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +" has released LockCustom.");
lockCustom.unlock();
}
}
interface LockCustom {
void lock();
void unlock();
boolean tryLock();
}
class ReentrantLockCustom implements LockCustom {
int lockHoldCount;
long lockingThreadId;
ReentrantLockCustom() {
lockHoldCount = 0;
}
public synchronized void lock() {
if (lockHoldCount == 0) {
lockHoldCount++;
lockingThreadId = Thread.currentThread().getId();
} else if (lockHoldCount > 0 && lockingThreadId == Thread.currentThread().getId()) {
lockHoldCount++;
} else {
try {
wait();
lockHoldCount++;
lockingThreadId = Thread.currentThread().getId();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void unlock() {
if (lockHoldCount == 0)
throw new IllegalMonitorStateException();
lockHoldCount--;
if (lockHoldCount == 0)
notify();
}
public synchronized boolean tryLock() {
if (lockHoldCount == 0) {
lock();
return true;
} else
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment