Ensuring all waiting threads complete

Posted by Daniel on Stack Overflow See other posts from Stack Overflow or by Daniel
Published on 2013-11-08T19:43:32Z Indexed on 2013/11/09 21:54 UTC
Read the original article Hit count: 212

Filed under:
|
|

I'm building a system where the progress of calling threads is dependent on the state of two variables. One variable is updated sporadically by an external source (separate from the client threads) and multiple client threads block on a condition of both variables. The system is something like this

TypeB waitForB() { // Can be called by many threads.
    synchronized (B) {
        while (A <= B) { B.wait(); }
        A = B;
        return B;
    {
}

void updateB(TypeB newB) { // Called by one thread.
    synchronized (B) {
        B.update(newB);
        B.notifyAll(); // All blocked threads must receive new B.
    }
}

I need all the blocked threads to receive the new value of B once it has been updated. But the problem is once a single thread finishes and updates A, the waiting condition becomes true again so some of the other threads become blocked and don't receive the new value of B. Is there a way of ensuring that only the last thread that was blocked on B updates A, or another way of getting this behaviour?

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading