×

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

Non-primitive data types in Java

The kind of data stored in the variable is determined by its type. The type describes the data category (different sizes and values). These are not already built into the devices....

4 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 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.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.