Ad

Java Concurrency Barrier Example Deadlock

I am trying to implement custom Barrier example in order to learn more about concurrency in Java. I have a runnable class:

public class Barrier implements Runnable {

    private static Semaphore barrier = new Semaphore(0);
    private static int toWait = 5;
    private static int counter = 0;

    private static long sleepTime;

    public static int ID = 0;

    private int id = ++ID;

    public Barrier(long sleep){
        sleepTime = sleep;
    }

    @Override
    public void run() {

        try {

            Thread.sleep(sleepTime);

            counter++;
            if (counter == toWait){
                barrier.release(counter);
            }
            barrier.acquire();

            System.out.println("Thread with sleep: " + id + " proceeds");

        } catch (InterruptedException ex) {
            Logger.getLogger(Barrier.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

Then in the main function, I create 5 threads and start them. Upon, running I get a deadlock, that I can't resolve. Can someone tell me what I am doing wrong?

Ad

Answer

There were no mutual exclusion. To solve it, I needed to add another semaphore and surround the counter increment with with acquirerelease of that semaphore.

Ad
source: stackoverflow.com
Ad