About 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.

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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


1 × five =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books