javamultithreadingconcurrencyconcurrent-programming

How to code the dining Philosophers in Java using semaphores?


I have to code a solution to the dining philosophers problem in Java using semaphores. The semaphore is done "by hand" creating a semaphore class. And looks like this:

package principal;
public class Semaforo {
private int valor;
private int esperando;
public Semaforo(int valor) {
    this.valor=valor;
    this.esperando=0;
}
public synchronized void down() {
    if (this.valor >0 ){
        this.valor--;
    } else {
        this.esperando++;
        try {
            wait();
        } catch (Exception e) {

        }
    }
}
public int getValor() {
    return valor;
}
public synchronized void up() {
    if (this.valor > 0) {
        this.valor++;
    } else {
        if (this.esperando >0 ) {
            notify();
            this.esperando--;
        } else {
            this.valor++;
        }
    }
}
}

I would be nice if I had a solution that avoids problems of concurrency like deadlocks, starvation, live-locks, and so on. I thought of having each philosopher eat at his own time, but I don't know how I could accomplish that with semaphores. How do I solve the dinning philosophers problem with semaphores in Java?

Any help is appreciated.


Solution

  • This (page 87) goes over the Dining Philosophers problem taken from Tanenbaum's Modern Operating Systems 3e. The problem is solved with sempahores in the C programming language.