Leetcode 1226. The Dining Philosophers (Medium)

Kostya
1 min readFeb 17, 2021

This is a kind of task that real leetcoder has a hard time to deal with :) Instead of academic algorithms this is more focused on understanding how real computers work. Meet The Dining Philosophers https://leetcode.com/problems/the-dining-philosophers/. The actual problem is very old, solved in real OSs and described in Operating Systems Design and Implementation by A. Tanebaum.

I read through discussion to the task and apparently most of people are posting clearly not working solutions that leads to deadlock and they seems to pass only because of concurrent programing is hard, but testing is even harder.

Here is my take on it:

class DiningPhilosophers {private final Random rnd = new Random();    
private ReentrantLock[] forks = new ReentrantLock[5];

public DiningPhilosophers() {
for(int i = 0; i < 5; i++) {
forks[i] = new ReentrantLock();
}
}
// call the run() method of any runnable to execute its code
public void wantsToEat(int philosopher,
Runnable pickLeftFork,
Runnable pickRightFork,
Runnable eat,
Runnable putLeftFork,
Runnable putRightFork) throws InterruptedException {

ReentrantLock rightFork = forks[philosopher];
ReentrantLock leftFork = forks[(philosopher + 1) % 5];

boolean lf = false, rf = false;

do {
rf = rightFork.tryLock(rnd.nextInt(100)+50, TimeUnit.MILLISECONDS);
lf = leftFork.tryLock(rnd.nextInt(100)+50, TimeUnit.MILLISECONDS);
if(rf && !lf) {
rf = false;
rightFork.unlock();
}
} while(!(lf && rf));

try{
pickRightFork.run();
pickLeftFork.run();
eat.run();

putLeftFork.run();
putRightFork.run();
} finally {
rightFork.unlock();
leftFork.unlock();
}

}
}

--

--

Kostya

Java, start-up, hiking, photos, bicycle,journey