Tuesday, May 22, 2012

Playing PingPong with STM - Refs and Agents

PingPong is a classic example where 2 players (or threads) access a shared resource - PingPong Table and pass the Ball (state variable) between each other. With any shared resource, unless we synchronize the access, the threads can run into potential deadlock situation.

The PingPong algorithm is very simple

if my turn {
     update whose turn is next
     ping/pong - log the hit
     notify other threads
} else {
    wait for notification

Let's take an example and see how this works! Here is our Player class, which implements Runnable and takes in the access to the shared resource and a message

Tuesday, May 8, 2012

Using TestKit with Java

Unit testing toolkit is provided via TestKit in Akka. The scala side of unit testing is well covered. For java, TestKit provides limited constructs. The various examples implemented by Ray Roestenburg have been ported to Java world, with couple of more scenario's added. This can be good starting point for Java programmers to start unit testing their actors.

Let’s check out some testing code which tests out the following different set of actors
  • Echo Actor – responds back with whatever is passed to the actor
  • Forwarding Actor – forwards the message to another actor
  • Sequencing Actor – replies back in a series of messages but assuming we are interested in one
  • Filtering Actor – replies back for certain messages and ignores the others
  • Boom Actor – throws an exception when a message is send
  • Supervisor Actor – manages an another worker actor, and based on the exception thrown by the worker actor, applies the appropriate supervisor strategy