Dining Philosophers

Hard
ConcurrencyMutexSemaphoreDeadlockStarvationResource 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 i is between philosopher i and (i+1)%5.
  • Mutex per fork: ReentrantLock or Semaphore(1) per fork.
  • Deadlock prevention strategy: Resource ordering, arbitrator, or capacity limiting.

Requirements

  1. No deadlock — philosophers must not all hold one fork and wait for the other indefinitely.
  2. No starvation — every philosopher eventually gets to eat.
  3. Maximum concurrency — allow multiple philosophers to eat simultaneously where possible.
  4. 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.