Some Coding Challenges: Implementing a Lock.

applied.math.coding
2 min readMar 27, 2024

The challenge is to implement a lock in Java by only using synchronized, wait, notify as constructs.

The lock shall work as follows:

var lock = new Lock();

private void doSomething(){
lock.lock();
// no other thread shall be able to go here in the meantime
lock.unlock();
}

A solution written in Java:

class Lock {
boolean isLocked = false;

public synchronized void lock() {
while (isLocked) {
try {
wait();
} catch (InterruptedException e) {
// neglect
}
}
isLocked = true;
}

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

You can use this like so:

var task = new Runnable() {
Lock countLock = new Lock();
int count = 0;

@Override
public void run() {
while (true) {
countLock.lock();
if (count < 1000) {
count += 1;
System.out.println(Thread.currentThread().getName() + " :" + count);
} else {
countLock.unlock();
break;
}
countLock.unlock();
}
System.out.println("finished " + Thread.currentThread().getName());
}
};

(new Thread(task)).start();
(new Thread(task)).start();

--

--

applied.math.coding
applied.math.coding

Written by applied.math.coding

I am a Software Developer - Java, Rust, SQL, TypeScript - with strong interest doing research in pure and applied Mathematics.