Question

I have a simple "play/pause" flag. Imagine a doer thread:

 private final Thread backgroundDoer = new Thread(() -> {
       while(true) {
           doOperation();
           playFlag.await();
       }
})

So keep doing an operation unless the flag is false, in which case wait for the flag to be true to continue.

My question is how to do this properly in Java. I can't really use a Condition because I would need to keep signalling it from outside. Right now I am using a Semaphore. When "play" is pressed I give it a lot of permits, when pause is pressed I drain them all away. It seems clunky and stupid though. Any better ways?

Was it helpful?

Solution

You could simply acquire the permit (use a binary Semaphore) and release it immediately.

If things haven't been paused, it will simply acquire and return it (allowing the pause to acquire it if called), continuing with the operation. But if pause has happened, it will block as soon as acquire is attempted.

while(true) {
    doOperation();
    semaphore.acquire();   // Block if paused
    semaphore.release();   // Release immediately, so pause() can acquire() the semaphore
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top