0

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?

CarrKnight
  • 2,768
  • 2
  • 23
  • 25
  • 3
    Wait... `Semaphore` doesn't have an `await()` method. Do you have several background threads and that's why you're using several permits? – Kayaman Apr 11 '14 at 16:59
  • The await there is really pseudocode for what I'd like. There is only one background thread. Thats why I'd really like not to use a semaphore, rather just a condition I could set once and it wouldn't block until I tell it to – CarrKnight Apr 11 '14 at 17:06
  • 1
    this is not neither clunky nor stupid. This is exactly what semaphores are supposed to do. The only note is that you need counting semaphore, not binary, and the operation is called acquire(), not await(). – Alexei Kaigorodov Apr 11 '14 at 17:09
  • thanks, what feels clunky to me is that I'd really like to give "infinite permits" since there is no particular reason to give a discrete number. I am going to try Kayaman answer which looks simple and effective – CarrKnight Apr 11 '14 at 17:51

1 Answers1

1

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
}
Kayaman
  • 72,141
  • 5
  • 83
  • 121