Enterprise Java

Akka STM – 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

  

 
 
 public class Player implements Runnable {
  PingPong myTable;  Table where they play
  String myOpponent;
 
  public Player(String opponent, PingPong table) {
   myTable = table;
   myOpponent = opponent;
  }
 
  public void run() {
   while (myTable.hit(myOpponent))
    ;
  }

 }

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.

  
 
 public class PingPong {
   state variable identifying whose turn it is.
  private String whoseTurn = null;
 
  public synchronized boolean hit(String opponent) {
 
   String x = Thread.currentThread().getName();
 
   if (x.compareTo(whoseTurn) == 0) {
    System.out.println('PING! (' + x + ')');
    whoseTurn = opponent;
    notifyAll();
   } else {
   try {  wait(2500); } 
   catch (InterruptedException e) { }
   }
   }
 }

Next, we start the game and get the players started!

  

 
 
 public class Game {
  public static void main(String args[]) {
   PingPong table = new PingPong();
   Thread alice = new Thread(new Player('bob', table));
   Thread bob = new Thread(new Player('alice', table));
 
   alice.setName('alice');
   bob.setName('bob');
   alice.start();  alice starts playing
   bob.start();  bob starts playing
   try {
     Wait 5 seconds
    Thread.sleep(5000);
   } catch (InterruptedException e) {
   }
 
   table.hit('DONE');  cause the players to quit their threads.
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
   }
  }
 }

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.

  

 
 
 public class PingPong {
 
  updates to Ref.View are synchronous
  Ref.View<String> whoseTurn;
 
  public PingPong(Ref.View<String> player) {
   whoseTurn = player;
  }
 
  public boolean hit(final String opponent) {
   final String x = Thread.currentThread().getName();
 
   if (x.compareTo(whoseTurn.get()) == 0) {
    System.out.println('PING! (' + x + ')');
    whoseTurn.set(opponent);
   } else {
    try {
     wait(2500);
           } catch (Exception e) {
    }
   }
 }
 }

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.

  

 
 
 public class PingPong {
 
  Agent<String> whoseTurn;
 
  public PingPong(Agent<String> player) {
   whoseTurn = player;
  }
 
  public boolean hit(final String opponent) {
   final String x = Thread.currentThread().getName();
 
   wait till all the messages are processed to make 
   you get the correct value, as updated to Agents are
   async
   String result = whoseTurn.await(new Timeout(5, SECONDS));
 
   if (x.compareTo(result) == 0) {
    System.out.println('PING! (' + x + ')');
    whoseTurn.send(opponent);
   } else {
    try {
     wait(2500);
 
    } catch (Exception e) {
    }
   }
   return true;  keep playing.
  }
 }

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

Reference: Playing PingPong with STM – Refs and Agents from our JCG partner Munish K Gupta at the Akka Essentials blog.

Munish Gupta

Munish K Gupta is a senior architect working in a leading IT services company. His experience is in building Online Portals, SaaS Platforms, CRM Solutions and Transaction Processing Systems. He is author of the book - Akka Essentials.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button