Search code examples
javaconcurrencycyclicbarrier

Java - gracefully quit threads


I got a bunch of threads that perform calculations. They are "synchronized" using a CyclicBarrier. When any thread's run() method finishes, I want all other threads to exit as well once they call await() on the barrier the next time.

So far, everything I've tried either hangs at the await() calls or results in a broken barrier. Any tips?

EDIT: Here's the (basic) code:

public MyClass implements Runnable {
    public void run() {
        while (true) {
            if (someCondition) {
                // quit other threads when they call await()
                return;
            }
            barrier.await();
    }
}

Solution

  • reset() will awaken all waiting threads with a thrown exception

    you can then use the await as so

    private static volatile boolean shouldStop=false;
    
    public void run() {
        try{
            while (true) {
                if (someCondition) {
                    // quit other threads when they call await()
                    return;
                }
                try{
                    if(shouldStop)return;
                    barrier.await();
                }catch(BrokenBarrierException e){
                    //someone stopped 
                    return;
                }
           }
       }finally{
           shouldStop =true;
           barrier.reset();
       }
    }
    

    you can also call a method for the if(shouldStop) check