Note that there are some explanatory texts on larger screens.

plurals
  1. POBlocking and simultaneously releasing a variable number of threads in Java
    text
    copied!<p>I'm building a buffer in Java that will collect write actions requested by many threads, and flush them as a group, say, once per second. I'd like to give it a method called <code>waitForFlush</code> that will block and thread that calls it until the next flush event completes. Meanwhile, a separate, standalone thread is flushing and sleeping in a loop. So I'm basically looking for a concurrency structure or pattern that will allow many threads to block at a particular point, and then release them all simultaneously, and I'm finding that none of Java's builtin concurrency primitives are a really close match for this. The best I've come up with so far is wait/notifyAll, as follows:</p> <pre><code>public class Buffer { private volatile long lastFlushTime = System.currentTimeMillis(); private final Object flushMonitor = new Object(); public void waitForFlush() { long entryTime = System.currentTimeMillis(); synchronized(flushMonitor) { while(lastFlushTime &lt;= entryTime) { flushMonitor.wait(); } } } public void flush() { // do flush stuff here synchronized(flushMonitor) { lastFlushTime = System.currentTimeMillis(); flushMonitor.notifyAll(); } } } </code></pre> <p>Although I think this would work fine in practice, the synchronization block in <code>waitForNotify()</code> still feels somewhat imperfect to me. Ideally, for this use case, you would be able to call <code>wait()</code> without synchronizing on the associated Object, and all of the blocked threads would be released at the precise same moment when <code>notifyAll()</code> is called, instead of having to exit the synchronized block one-by-one.</p> <p>So, in general, is there a better way to block and simultaneously release a variable number of threads than I've outlined above (the Semaphore and CountDownLatch classes would only work for for a fixed number of threads, I think)?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload