views:

218

answers:

2

What's the closest thing in Java (perhaps an idiom) to threading.Event in Python?

+5  A: 

The Object.wait() Object.notify()/Object.notifyAll().

Or Condition.await() and Condition.signal()/Condition.signalAll() for Java 5+.

Edit: Because the python specification is similar how we usually wait a Java implementation would look like this:

class Event {
    Lock lock = new ReentrantLock();
    Condition cond = lock.newCondition();
    boolean flag;
    public void doWait() throws InterruptedException {
        lock.lock();
        try {
            while (!flag) {
                cond.await();
            }
        } finally {
            lock.unlock();
        }
    }
    public void doWait(float seconds) throws InterruptedException {
        lock.lock();
        try {
            while (!flag) {
                cond.await((int)(seconds * 1000), TimeUnit.MILLISECONDS);
            }
        } finally {
            lock.unlock();
        }
    }
    public boolean isSet() {
        lock.lock();
        try {
            return flag;
        } finally {
            lock.unlock();
        }
    }
    public void set() {
        lock.lock();
        try {
            flag = true;
            cond.signalAll();
        } finally {
            lock.unlock();
        }
    }
    public void clear() {
        lock.lock();
        try {
            flag = false;
            cond.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
kd304
Please don't suggest wait() and notify(). Somebody might use them.
Michael Myers
Thanks, I will go with java.util.concurrent.Condition
shikhar
Just saw your edit with the example Event implementation, wonderful! Thanks a lot.
shikhar
A: 

A related thread. There is a comment on the accepted answer which suggests a Semaphore or a Latch. Not the same semantics as the above implementation, but handy.

shikhar
Note that the operational behavior of the Semaphore differs from the Event object you asked.
kd304
yes, just noted that :-)
shikhar