Dining Philosophers
HardConcurrencyMutexSemaphoreDeadlockStarvationResource Ordering
Problem Statement
Five philosophers sit around a circular table. Between each adjacent pair of philosophers lies one fork (chopstick). A philosopher alternates between thinking and eating. To eat, a philosopher must pick up both the left and right forks. After eating, both forks are returned.
Design a solution that allows the philosophers to eat without deadlock and without starvation.
class DiningPhilosophers {
public DiningPhilosophers() {}
// Called concurrently by 5 threads (one per philosopher)
public void wantsToEat(int philosopher,
Runnable pickLeftFork,
Runnable pickRightFork,
Runnable eat,
Runnable putLeftFork,
Runnable putRightFork) throws InterruptedException {}
}
Key Entities
- 5 Philosophers: Threads indexed 0–4.
- 5 Forks: Shared resources; fork
iis between philosopheriand(i+1)%5. - Mutex per fork: ReentrantLock or Semaphore(1) per fork.
- Deadlock prevention strategy: Resource ordering, arbitrator, or capacity limiting.
Requirements
- No deadlock — philosophers must not all hold one fork and wait for the other indefinitely.
- No starvation — every philosopher eventually gets to eat.
- Maximum concurrency — allow multiple philosophers to eat simultaneously where possible.
- Solution should work for N philosophers (generalized).
Asked at: Google, Amazon, Microsoft, Facebook, Apple, Uber, Oracle
!Constraints
- n = 5 philosophers, 5 forks in the standard problem.
- Each philosopher thread calls wantsToEat() in a continuous loop.
- Runnable callbacks must be called in order: pickLeft, pickRight, eat, putLeft, putRight.
- Solution must be deadlock-free and starvation-free.
Output
Run or submit your code to see output here.