Java 2013 fuse day Impressions

Java 2013 fuse day Impressions:

 

During the fuse day our java group was learning to use Akka framework for creating a multiplayer snake online game

Prior to selecting akka as the main study feature of this fuse day I've given a short lecture about the concepts of Actor-based solution to concurrency development.

What is Akka ?!

Well  - akka aims to be the platform for the next-generation, event-driven, scalable, and fault-tolerant architectures on the JVM.

Akka in a nutshell

One of the core features of Akka is an implementation of the Actor model. It alleviates the developer from having to deal with explicit locking and thread management. Using the Actor model raises the abstraction level and provides a better platform for building correct concurrent and scalable applications.

 

Actors in akka:

 

Actors:

·         Simple and high-level abstractions for concurrency and parallelism.

·         Asynchronous, non-blocking and highly performant event-driven programming model.

·         Very lightweight event-driven processes (approximately 2.7 million actors per GB RAM).

 

Fault Tolerance:

·         Supervisor hierarchies with "let-it-crash" semantics (parent actor supervising child actors(.

·         Supervisor hierarchies can span over multiple JVMs to provide truly fault-tolerant systems.

·         Excellent for writing highly fault-tolerant systems that self-heal and never stop.

 

Location Transparency:

·         Everything in Akka is designed to work in a distributed environment: all interactions between actors use pure message passing and everything is asynchronous.

 

Akka & Scala

Akka was developed in scala & has a java counterpart API for the non-scala developers, the Java API covers most of the akka features.

 

Fuse Day & Team preparations

Learning Curve

Since learning both akka & scala in a single day is not feasible we decided to concentrate on akka main features with java.

To make the day efficient and productive I've prepared a maven based working skeleton for facilitate the java-akka server side .

See git-hub repository https://github.com/tikalk/fuse-jun13-akka-java.git

 

Our team was responsible for making the concurrent multiplayer code that would interact with the browser via Play-framework web-sockets and activate the scala based API to calculate positions;

Game Architecture

The "Game Architecture" was as follows:

Play framework was to send async messages to the root game actor:

   ** indicating  user registration

   ** start game

   ** end  game

   ** user move request

 

The server side actors:

 ** GameMaster - root actor parent of all actors holding the state of the game

 ** User - representing each concurrent user

 

 

The Heartbeat:

The snake game is time based and therefore we created a scheduler for ticking the game's heartbeat.

On each heartbeat:

  * root actor:

       ** gathers the players move requests

       ** calls scala API for game board positions calculations

       ** callback the play for UI drawing for the web players

 

We also have async events arriving from the players with move requests;

On each player move request:

* user actor:

   ** change internal state representing the last move request

 

Akka Key components:

 

The project consisted of the next main akka components:

  system-actor -  responsible for managing actors

  even-bus  -       responsible for pub/sub communications between actors

  scheduler -       responsible for heartbeat timing of the game

 

// init master and initial user-actors

public void init() {

         // Create an Akka system

         system = ActorSystem.create("SnakeGame");

         // system scheduler

         final Scheduler scheduler = system.scheduler();

         // get event stream

         final EventStream eventStream = system.eventStream();

         master = system.actorOf(new Props().withCreator((Creator)new GameMaster.MasterCreator(scheduler, eventStream, callback)), "master");

 

         // resigter event bus master messages

         eventStream.subscribe(master, Register.class);

         eventStream.subscribe(master, StartGame.class);

         eventStream.subscribe(master, Tick.class);

}

 

This code shows the initiation of actor system and root actor creation

 

 

The next code shows the User actor receive call api:

@Override
public void onReceive(Object message) throws Exception {
   log.debug("user " + getSelf().path() + " receive message [" + message + "] ");
      if (message instanceof MoveSnake.Direction) {
            this.direction = (MoveSnake.Direction) message;
      } else if (message instanceof GetSnakePosition) {
         getSender().tell(new SnakePosition(register,location,snakeLength,direction), getSelf());
      } else if (message instanceof Terminated) {
            getContext().stop(getSelf());
            log.info("user " + getSelf().path() + " Terminated ");
       } else {
            unhandled(message);
       }
  }

 

In this example Its simple to see that the actor is changing his internal state or reacting to events.

Akka Pub/Sub

We also used akka's pub/sub api which is a simple form of multicast event to multiple subscribers based on selective message type registration.

 

The Ask Pattern

Another interesting feature we've used in our game is the "ask" pattern; this pattern help us wait on multiple actors to respond for a specific request:

Map<Player, String> moves = new HashMap<Player, String>();
for (ActorRef userActorRef : usersActorRefs) {
Timeout timeout = new Timeout(Duration.create(100,  TimeUnit.MILLISECONDS));
Future<Object> future = Patterns.ask(userActorRef, new GetSnakePosition(),  timeout);
         try {
SnakePosition snakePosition = (SnakePosition) Await.result(future, timeout.duration());
moves.put(new Player(snakePosition.getUser().getName()), snakePosition.getDirection().name());
         } catch (Exception e) {
                 e.printStackTrace();
         }
}

 

In this example we create a "blocking barrier" on the actor's response so that we can aggregate their response to a single state - in this case our users game-board moves.

 

During the Day

First we started by a short review and introduction of the skeleton components and how/what we should attempt to achieve this day;

Second we started running and playing around with akka's events and actor to get familiar with the code and ideas.

Soon enough people stated coding and we completed our tasks, most of our issues concerned integrating with the other groups (Play & Scala) and selecting implementation for the game's specific behavior.

 

In conclusion:

·         We showed that writing concurrent code is very simple using akka & its actors model - once you get its concept

·         Most of our application's use cases are well within akka's examples and patterns

·         We can use the code we've created as a basis for future study and concurrent game platform development

·         It is important to continue studying additional concurrency development concepts (apart from the standard java threading) and do a full day course on akka

 

 Lior

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com