- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Actor-CountdownLatch equivalent
Tue, 2009-06-30, 00:09
Actor-CountdownLatch equivalent
Hi Folks,
I am trying to figure out how a Java CountdownLatch would best be implemented in Scala. I was thinking of a couple of options:
I think either of these would work, but it seems like there ought to be a more elegant solution or perhaps there’s a solution built in to the actors library that I haven’t discovered. Any suggestions?
Thanks,
Mark
I am trying to figure out how a Java CountdownLatch would best be implemented in Scala. I was thinking of a couple of options:
- Have a controller actor that increments the message count as ! is called and decrements when a return value is sent.
- Fire off a bunch of futures and do something with logic like “while all futures haven’t completed keep looping.”
I think either of these would work, but it seems like there ought to be a more elegant solution or perhaps there’s a solution built in to the actors library that I haven’t discovered. Any suggestions?
Thanks,
Mark
It depends on what you're trying to accomplish. If you're trying to implement a CountDownLatch on which threads will block, meaning something basically the same as Java's CountDownLatch, then I would just use Java's CountDownLatch. You could wrap it in a more Scala-like object (e.g. using "count" instead of "getCount").
If you're trying to do something like a CountDownLatch, only that will work will with event-based actors, meaning instead of blocking actors suspend until the countdown hits zero, and then they are all woken up, then I'd make a CountDown actor that processes two types of messages:
- RequestNotification - tells the CountDown actor to message the sender when the countdown is complete. If the countdown is already complete, reply right away
- Decrement - tells the CountDown actor to decrement the counter. If the counter hits zero, then notifications are sent.
Actors using the CountDown actor would message it with RequestNotification and then immediately suspend until they received a notification.
Please note that the actor-based solution adds significant overhead for a blocking latch over what's in java.util.concurrent, so it only becomes worthwhile if you can free the threads to do other work while waiting on the latch.
-Erik
On Mon, Jun 29, 2009 at 7:08 PM, Bastian, Mark <mbastia@sandia.gov> wrote:
--
http://erikengbrecht.blogspot.com/