×

Dining Philosophers problem in Java

The Problem of the Dining Philosophers illustrates a concurrency issue involving the distribution of scarce resources among conflicting processes.

Problem Statement

Imagine a dining table with a circle in the middle and five philosophers seated there. The illustration below shows that the dining table contains five chopsticks and a bowl of rice in the center.

Dining Philosophers problem in Java

A philosopher is either eating or thinking at any given time. A philosopher uses one chopstick from their left and one from their right when he wants to eat. A philosopher places both chopsticks back where they were when he wants to reflect. All philosophers start out by thinking. After a while, he becomes hungry and desires noodles. The philosopher scans both sides for the forks. The philosopher begins to eat after receiving both forks. He finishes his meal, sets the forks down, and resumes pondering. The forks that the philosopher sets down may be used by nearby philosophers.

The issue is utilized to create a scheduling method that ensures no philosopher will go hungry.

The following conditions must be followed:

  • A philosopher will eat with both chopsticks (left and right).
  • Any one of the nearby philosophers may choose the remaining branch, but not both.
  • As long as both forks are accessible, a philosopher may eat noodles.
  • A philosopher will set both forks down after eating and resume pondering.
  • The other philosophers can choose those forks and proceed with the same method.
  • Right and left philosophical neighbors are not permitted to eat together.

Approach

Dining Philosopher’s Problem in Practice

First, we have initialized the number of philosophers in the following application. The number of philosophers was the initial value for the two arrays, philosophers[] and chopsticks[].

We've constructed a class called Chopstick to implement the logic for chopsticks.

The acquire() method, which obtains a permit from this semaphore, is called the grab() method. It eliminates 1 permit from the system. If no permits are available, the active thread is disabled.

The release() function of the Semaphore class is called by the user-defined release() method. It issues the specified number of licences and advances each one by one.

Program

DiningPhilosophereProblem.java

// importing the required packages
import java.util.concurrent.Semaphore;  
import java.util.concurrent.ThreadLocalRandom; 
// Main class declaration 
public class DiningPhilosophersProblem  
{  
static int philosopher = 5;  
static Philosopher p[] = new Philosopher[philosopher];  
static Chopstick c[] = new Chopstick[philosopher];  
static class Chopstick   
{  
public Semaphore m = new Semaphore(1);  
void grab()   
{  
// try block is used to prevent the stop of program execution due to errors
try   
{  
m.acquire();  
}  
catch (Exception ex)   
{  
ex.printStackTrace(System.out);  
}
}  
// release method 
void release()   
{    
m.release();  
}   
// Boolean variable isFree() is used to check whether the chopstick is free or not
boolean isFree()   
{  
return m.availablePermits() > 0;  
}  
} 
// extending to thread class
static class Philosopher extends Thread   
{  
public int n;  
public Chopstick leftchopstick;  
public Chopstick rightchopstick;  
Philosopher(int num, Chopstick left, Chopstick right)   
{  
n = num;  
leftchopstick = left;  
rightchopstick = right;  
}  
// run method to run the thread
public void run()  
{  
while (true)   
{  
leftchopstick.grab();  
System.out.println("Philosopher " + (n+1) + " holds left chopstick.");  
rightchopstick.grab();  
System.out.println("Philosopher " + (n+1) + " holds right chopstick.");  
   
eat();  
  
leftchopstick.release();  
System.out.println("Philosopher " + (n+1) + " releases left chopstick.");  
rightchopstick.release();  
System.out.println("Philosopher " + (n+1) + " releases right chopstick.");  
}   
}   
void eat()   
{  
try   
{  
int sleepTime = ThreadLocalRandom.current().nextInt(0, 1000);  
System.out.println("Philosopher " + (n+1) + " eats for " + sleepTime +"ms");   
Thread.sleep(sleepTime);  
}  
catch (Exception ex)   
{  
ex.printStackTrace(System.out);  
}  
} 
}  
public static void main(String args[])   
{  
for (int i = 0; i < philosopher; i++)   
{  
c[i] = new Chopstick();  
} 
for (int i = 0; i < philosopher; i++)   
{  
p[i] = new Philosopher(i, c[i], c[(i + 1) % philosopher]);  
p[i].start();  
}   
while (true)   
{  
try   
{  
Thread.sleep(1000);  
boolean dl = true;  
for (Chopstick ct : c)   
{  
if (ct.isFree())   
{  
dl = false;  
break;  
}   
}  
if(dl)   
{  
Thread.sleep(1000);  
System.out.println("Everyone Eats");  
break;  
}   
}  
catch (Exception ex)   
{  
ex.printStackTrace(System.out);  
}  
}  
System.out.println("Exit The Program!");  
System.exit(0);  
}  
}

Output

Philosopher 1 holds left chopstick.
Philosopher 3 holds left chopstick.
Philosopher 5 holds left chopstick.
Philosopher 4 holds left chopstick.
Philosopher 2 holds left chopstick.
Everyone Eats
Exit The Program!

Related Topics

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

Factorial Program in Java using Recursion

Factorial Program in Java Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to...

3 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.