goldwin-es
goldwin-es

Reputation: 996

Java synchronization primitive

I want the following semaphore-like synchronization primitive in my code:

class Event {
    private boolean fired = false;

    public synchronized void fire() {
        this.fired = true;
        this.notify();
    }

    public synchronized void waitFor() throws InterruptedException {
        while (!this.fired)
            wait();
        this.fired = false;
    }
}

Is there a primitive in Java standard library (or other popular libraries) that can be used with the same semantics?

EDIT: It seems that CountDownLatch is the best possible candidate, so I'm going to accept one of the answers. Although I don't like it in this case because it doesn't provide clear semantics and lacks readability.

Upvotes: 3

Views: 1504

Answers (2)

Jaroslaw Pawlak
Jaroslaw Pawlak

Reputation: 5578

You may want to use CountDownLatch. Initialize with 1 cdl = new CountDownLatch(1), waiting thread will call blocking method cdl.await() while the notifying thread will call cdl.countDown().

You will have to create new CountDownLatch object as it doesn't have reset method. It's worth to remember about memory consistency errors, but in your case all methods accessing this variable are synchronised so it won't be a problem.

Alternatively, you can use CyclicBarier and then all threads will be calling cb.await(). Initialise it with the number of threads cb = new CyclicBarrier(2) and then method await will block until 2 threads are waiting and will let only these 2 threads go forward.

Upvotes: 0

seahawk
seahawk

Reputation: 1912

java.util.concurrent provides high level concurrency.

CountDownLatch will resolve your query.

Please go through docuementation

Upvotes: 3

Related Questions