Created
November 9, 2021 08:56
-
-
Save mahadevshindhe/fe4022702ce821397e90da4313cde4ad to your computer and use it in GitHub Desktop.
Java Custom Re Entrant Lock implmentation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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