Create Custom Lock In Java

May 15, 2018 by Sandeep Bhardwaj | Tags:


Lock.java

public class Lock {

	private boolean isLocked = false;

	public synchronized void lock() throws InterruptedException {
		while (isLocked) {
			wait();
		}
		isLocked = true;
	}

	public synchronized void unlock() {
		isLocked = false;
		notify();
	}
}

Usage

lock.lock();
try {
  // ... method body
} finally {
  lock.unlock();
}