Java Reference
In-Depth Information
Once a philosopher finishes eating, he puts down both forks and starts thinking. A philosopher cannot pick up
a fork if his neighbor is using it. What happens if each of the five philosophers picks up one fork from his right and
waits for his left fork to be released by his neighbor? This would be a deadlock situation and no philosopher would be
able to eat. This deadlock condition can be avoided easily by using the tryLock() method of the Lock interface. This
method returns immediately and it never blocks. If the lock is available, it gets the lock and returns true . If the lock
is not available, it returns false . The class in Listing 6-31 can be used to model the philosophers assuming that an
object of the ReentrantLock class represents a fork.
Listing 6-31. A Philosopher Class to Represent a Philosopher
// Philosopher.java
package com.jdojo.threads;
import java.util.concurrent.locks.Lock;
public class Philosopher {
private Lock leftFork;
private Lock rightFork;
private String name; // Philosopher's name
public Philosopher(Lock leftFork, Lock rightFork, String name) {
this.leftFork = leftFork;
this.rightFork = rightFork;
this.name = name;
}
public void think() {
System.out.println(name + " is thinking...");
}
public void eat() {
// Try to get the left fork
if (leftFork.tryLock()) {
try {
// try to get the right fork
if (rightFork.tryLock()) {
try {
// Got both forks. Eat now
System.out.println(name + " is eating...");
}
finally {
// release the right fork
rightFork.unlock();
}
}
}
finally {
// release the left fork
leftFork.unlock();
}
}
}
}
Search WWH ::




Custom Search