diegoaguilar
diegoaguilar

Reputation: 8376

How can I implement this concurrency situation using java semaphores?

I want to implement this classic toilet room entrance problem using the semaphores provided by the java library.

The scenario is: there's a public bathroom which can be used by a maximum of 4 women and 5 men but never at the same time. Also, while there's at least one women waiting, men should wait so the women can get easier entrance.

So far I've modeled this concurrency class...

public class Concurrencia {

Semaphore mujeres;    // Semaphore for women, initialized in 4
Semaphore hombres;    // Semaphore for men, initialized in 5

public Concurrencia (Semaphore mujeres, Semaphore hombres) {

    this.mujeres = mujeres;
    this.hombres = hombres;

}

public synchronized void EntradaHombres () {    // Method for men's entrance

    if ( mujeres.availablePermits() == 4 && !mujeres.hasQueuedThreads() ) {
        System.out.println("Entró un hombre al baño");              // Man gets in
        try { hombres.acquire(); } catch (InterruptedException ex) { }
    }
    else {
        System.out.println("Hombre en espera");   // Man should wait

    }

}


public synchronized void EntradaMujeres () {    // Method for women's entrance

    if ( hombres.availablePermits() == 5) {
        System.out.println("Entró una mujer al baño");  // Woman gets in
        try { hombres.acquire(); } catch (InterruptedException ex) { }
    }

    else {
        System.out.println("Mujer en espera");   // Woman should wait
    }

}


public synchronized void SalidaMujeres () {

    System.out.println("Salió una mujer del baño");
    mujeres.release();    // Woman gets out
}

public synchronized void SalidaHombres () {

    System.out.println("Salió un hombre del baño");
    hombres.release();    // Man gets out
}

Upvotes: 1

Views: 229

Answers (1)

irreputable
irreputable

Reputation: 45433

This might work:

First, without favoring women

men = new Semaphore(5, true),    women = new Semaphore(4, true);

void manEnter()                  void womanEnter()
    women.acquire(4);                women.acquire(1);
    men.acquire(1);                  men.acquire(5);
    women.release(4);                men.release(5);

void manExit()                   void womanExit()
    men.release(1);                  women.release(1);

To favor women, after a man succeeds, he must check if there are women waiting; if there are, he must release his permit and try again. We can't use the stats of women semaphore to check that condition, since men are also waiting onwomen permits. We can introduce an AtomicInteger to record number of women waiting. A semaphore can actually be used as an atomic integer. We might also be able to exploit negative permits in women to signal there are waiting women. This is becoming too complicated though, semaphore may not be the right tool for this problem.

Upvotes: 1

Related Questions