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





Second, we see the PingPong table class, which has a synchronized method hit() where a check is made, if my turn or not. If my turn, log the ping and update the shared variable for opponent name.


Next, we start the game and get the players started!
That's all, we have our PingPong game running. In this case, we saw how the synchronized method hit() allows only one thread to access the shared resource - whoseTurn.

Akka STM provides two constructs Refs and Agents. Refs (Transactional References) provide coordinated synchronous access to multiple identities. Agents provide uncoordinated asynchronous access to single identity.

Refs

In our case, since share state variable is a single identity, usage of Refs is overkill but still we will go ahead and see their usage.



The key here are the following
  • The synchronized keyword is missing
  • Definition of the state variable as Ref
    //updates to Ref.View are synchronous
    Ref.View<string> whoseTurn;
  • Calls to update Ref are coordinated and synchronous
    whoseTurn.set(opponent);
So, when we use the Ref to hold the state, access to the Refs is automatically synchronized in a transaction.

Agents

Since agents provide uncoordinated asynchronous access, using agents for state manipulation would mean that we need to wait till all the updates have been applied to the agent. Agents provide a non blocking access for gets.

The key here are the following
  • The synchronized keyword is missing
  • Definition of the state variable as Agent
    //updates to Ref.View are synchronous
    Agent<string> whoseTurn;
  • Wait for updates to the agent, as updates to agent are async
    String result = whoseTurn.await(new Timeout(5, SECONDS));
  • Calls to update Ref are coordinated and synchronous
    whoseTurn.send(opponent);
All the code referred in these example is available at - https://github.com/write2munish/Akka-Essentials/tree/master/AkkaSTMExample/src/main/java/org/akka/essentials/stm/pingpong with
Example 1 - for normal thread based synchronization
Example 2 - Usage of Refs for synchronization
Example 3 - Usage of Agents for synchronization

Trackback

loading..