Skip to content

Instantly share code, notes, and snippets.

@mahadevshindhe
Created November 9, 2021 08:56
Show Gist options
  • Select an option

  • Save mahadevshindhe/fe4022702ce821397e90da4313cde4ad to your computer and use it in GitHub Desktop.

Select an option

Save mahadevshindhe/fe4022702ce821397e90da4313cde4ad to your computer and use it in GitHub Desktop.

Revisions

  1. mahadevshindhe created this gist Nov 9, 2021.
    80 changes: 80 additions & 0 deletions CustomRentrantLock.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,80 @@
    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;
    }
    }