Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for an Actor to exit()

How do I wait for a Scala Actor to exit()? I set up two Actors in a unit test, and send a few messages to get them started. They send a few messages back and forth and eventually both call exit(). How do I make my unit test wait for both Actors to finish up before passing?

like image 868
Craig P. Motlin Avatar asked Jun 24 '10 04:06

Craig P. Motlin


2 Answers

If you know in advance the number of messages exchanged between the actors, you can use a java.util.concurrent.CountDownLatch to keep track of the count of messages. In the actors, after each processing of the message, do

latch.countDown()

and in your main thread do

latch.await()

This will make your main thread wait till the count of the latch is down to zero.

If you don't know the count of the messages in advance, but have a condition which indicates the finish, then you can use java.util.concurrent.locks.Condition. In the actors, when your condition is satisfied, do

if (conditionSatisfied)
  condition.signal()

and in your main thread do

while (!conditionSatisfied)
 condition.await()

to make it wait till the condition is satisfied.

See the javadocs of CountDownLatch and Condition for details.

See this Gist for example of using Condition.

like image 92
Abhinav Sarkar Avatar answered Sep 23 '22 06:09

Abhinav Sarkar


In Specs you can use Eventually Matchers. If you know the final state of your actor or any entity (say, persistence store) it modifies, you may force test to wait, until the switch to this state will occur:

<entity state> must eventually(10, 1.second)(be(<state>)) // there will be 10 retires every second, and if the state will be different, exception is thrown
like image 21
Vasil Remeniuk Avatar answered Sep 21 '22 06:09

Vasil Remeniuk