Meetu Maltiar's Blog

Meetu's thoughts on technology and software development

Bojug Meetup: Introducing Akka

leave a comment »


I presented this session on Introducing Akka at Bangalore Java Users Group. There was only one presentation today. The best part was that it was highly interactive session. We enjoyed it thoroughly. It lasted for more that two hours!!

This talk is inspired by Jonas Boner and Viktor Klang awesome presentations!!

My talk covered basics of Scala, Actors and Supervision. Code examples are found on my github. Here are the slides.

Written by Meetu Maltiar

June 28, 2014 at 20:15

Posted in Akka

Tagged with ,

Bojug Meetup: Getting Started With Scala

leave a comment »


I presented this session on Getting Started With Scala at Bangalore Java Open Users Group. There were three presentations that day:

  • JDK 1.8 by Bhavana Hindupur from Goldmansachs
  • Java Concurrency package by Vaibhav Choudhary and Srinivasan Raghavan from Oracle
  • Getting Started With Scala by me from Cisco

Sessions were well received and they were interactive. Thanks to the organisers for such a nice meet-up. Special thanks to Vineet Reynolds for helping me out that day.

My talk was meant for developers who wanted to get started on Scala. Sole objective was to get people started on creating a project in Scala, write some code using collections and test it using ScalaTest. Below are the slides and here are code samples on my github.

Written by Meetu Maltiar

April 30, 2014 at 14:40

Posted in Scala

Tagged with ,

FitNesse With Scala

leave a comment »


This time I gave a knowledge session on FitNesse. We have been using it for BDD and acceptance tests for projects at Knoldus. FitNesse is excellent for increasing collaboration between developers, testers and customers.

Making FitNesse work with Scala does not require any special configuration. It works out of the box. In this presentation you will learn using FitNesse for a Scala project with a DoFixture example. All code for this session is at Meetu’s github.

Written by Meetu Maltiar

August 3, 2013 at 08:35

Posted in Scala

Tagged with , ,

Akka Futures In Scala With A Simple Example

with one comment


We use Akka Futures extensively for a product built to handle huge load of streaming data. We have been early adopters of Akka and been using it right from its Akka 1.1.X days. We found Futures as simple yet powerful tool to add concurrent behavior in our application.

This post emphasizes importance of Akka Futures with a short and easy to understand example application. Please read excellent documentation on Akka Futures for more details.

Ok, now lets look at a simple example. Lets say we have an identity function. We sleep in it for a while to replicate long running nature. Here is the Scala code for the method.

def timeTakingIdentityFunction(number: Int) = {
    // we sleep for 3 seconds and return number
    Thread.sleep(3000)
    number
}

Suppose, we have an application in which we call timeTakingIdentityFunction method three times, gather their return in three variables and execute sum on them. Here is the code listing.

object SumApplication extends App {
  val startTime = System.currentTimeMillis
  val number1 = timeTakingIdentityFunction(1)
  val number2 = timeTakingIdentityFunction(2)
  val number3 = timeTakingIdentityFunction(3)
  val sum = number1 + number2 + number3
  val elapsedTime = ((System.currentTimeMillis - startTime) / 1000.0)
  println("Sum of 1, 2 and 3 is " + sum + " calculated in " + elapsedTime + " seconds")
 
  def timeTakingIdentityFunction(number: Int) = {
    // we sleep for 3 seconds and return number
    Thread.sleep(3000)
    number
  }
}

When we run this we will get around nine seconds to execute it. But what will happen when we do not block on timeTakingIdentityFunction?

Using Akka Futures we can do exactly that. When we do not block on timeTakingIdentityFunction and continue processing, we get performance boost. Now lets look at the Akka Futures version.

We can use Future directly, we wrap method call in a Future. In our example, we can do this in code.

val timeTakingIdentityFunctionFuture = Future(timeTakingIdentityFunction(1))

Since we are making three calls on timeTakingIdentityFunction. We can collect Future[Int] in three variables i.e. future1, future2, future3

val future1 = Future(timeTakingIdentityFunction(1))
val future2 = Future(timeTakingIdentityFunction(2))
val future3 = Future(timeTakingIdentityFunction(3))

Futures are monadic. We can compose them using for expressions. The future obtained by composing them can be used for calculating sum.

We will use onSuccess callback for this. Here is the code snippet.

 val future = for {
    x <- future1
    y <- future2
    z <- future3
  } yield (x + y + z)
 
future onSuccess {
    case sum =>
      val elapsedTime = ((System.currentTimeMillis - startTime) / 1000.0)
      println("Sum of 1, 2 and 3 is " + sum + " calculated in " + elapsedTime + " seconds")
  }

We composed a new Future out of three. The new composed Future is of type Future[Int]. We issued a callback to gather sum of three numbers. Here is the complete example.

import akka.dispatch.Future
import akka.actor.ActorSystem
 
object SumApplicationWithFutures extends App {
  implicit val system = ActorSystem("future")
  val startTime = System.currentTimeMillis
  val future1 = Future(timeTakingIdentityFunction(1))
  val future2 = Future(timeTakingIdentityFunction(2))
  val future3 = Future(timeTakingIdentityFunction(3))
 
  val future = for {
    x <- future1
    y <- future2
    z <- future3
  } yield (x + y + z)
 
  future onSuccess {
    case sum =>
      val elapsedTime = ((System.currentTimeMillis - startTime) / 1000.0)
      println("Sum of 1, 2 and 3 is " + sum + " calculated in " + elapsedTime + " seconds")
  }
 
  def timeTakingIdentityFunction(number: Int) = {
    // we sleep for 3 seconds and return number
    Thread.sleep(3000)
    number
  }
}

Only thing we have added here is implicit ActorSystem. Future requires an execution context. If ActorSystem is in implicit scope we are fine.

When we run Future version of the application it runs in about three seconds!!

Akka Futures can add benefit by adding concurrency in our applications. For example we might need to make three blocking Rest API calls to achieve a functionality. Depending on our use case we can avoid issuing blocking calls, but rather use Futures.

We used Futures directly in our example application. Since Futures are monadic we composed them using for expressions. We also used callback method to collect the result. And using them we got three times improvement in our code. Most importantly code is simple, concise and expressive.

There is more concise way to do this. We can construct List of Future[Int] and call Future.sequence to create or compose a single Future of List[Int]. Code is left as an exercise 🙂

Latest version of Akka 2.1.0 for Scala 2.10 has unified version of Future in Scala. This post pertains to Akka 2.0.5 version, concepts are still the same.

Written by Meetu Maltiar

August 2, 2013 at 08:09

Posted in Akka, Scala

Tagged with ,

Working With Akka FSM

leave a comment »


We can think Akka FSM as a set of relations. This is from Akka FSM documentation.
State(S) x Event(E) -> Actions(A), State(S’)
We can read it as: When an Actor is in a State(S) and an event(E) occurs. Then Actor performs Actions(A) and transitions to state(S’)

Let’s have a look at a simple example to understand how it works.

FSM actors are some sort of combination of their state and data. State are one of the states an FSM actor will be at a given snapshot of time. Data on the other hand represents state machine’s internal state. They will end up being type parameters used when we code FSM actor.

We begin with an example of State which can either be RED or GREEN. Below is the code defining them.

sealed trait State
case object RED extends State
case object GREEN extends State

For this simple example we may not need to work at all on Data. We could have used Int but we can use our definition as well. Let’s use Data class definition defined below.

case class Data

For an FSM actor that alternate to RED and GREEN we need to pass Event’s to it. For our scenario one event is enough to transition. Below is its message definition.

case class AlternateColor

So, we have built class definitions for Akka FSM actor. They are: states actor can be in, events that it will need to handle and the data. Now we can direct our attention to FSM actor.

To create FSM actor we need to mixin FSM trait to an actor. It takes in type parameters for State and Data. Below is the pseudocode of how we can use it.

class ColorFSMActor extends Actor with FSM[State, Data] {
  startWith(<"one of possible states">, <"some initial data like empty List">)

  when(<"one of possible states">) {
    // Some Code
  }

  // Transition elided
  when(<"one of possible states">) {
    // Some Code
  }

  ....

  onTransition {
    case <"one of possible states"> -> <"one of other possible states"> =>
      // Some Code
    .....
  }
  
  initialize
}

In our case we can start with a given state RED. We have two states, so we have two when block for each state. One for RED and one for GREEN.

Whenever FSM actor gets an Event of AlternateColor it changes its state to the other. There is also onTransition block that we can use. There is an arrow operator we can put between pair of states. For our case we can output a message via print line when state transitions from one to other.

Below is the complete implementation of the desired behavior.

class ColorFSMActor extends Actor with FSM[State, Data] {
  startWith(RED, Data())

  when(RED) {
    case Event(AlternateColor, _) => goto(GREEN)
  }

  when(GREEN) {
    case Event(AlternateColor, _) => goto(RED)
  }

  onTransition {
    case RED -> GREEN => println("I am in RED and going to GREEN")
    case GREEN -> RED => println("I am in GREEN and going to RED")
  }

  initialize
}

To see FSM actor in action we can create actor and send messages to it. We will see the print log of transition from RED to GREEN and from GREEN to RED. Below is the code snippet.

  val system = ActorSystem("fsm")
  val colorFSMActor = system.actorOf(Props[ColorFSMActor])
  (1 to 10) foreach { i => colorFSMActor ! AlternateColor }

you should see following in the logs:

I am in RED and going to GREEN
I am in GREEN and going to RED
I am in RED and going to GREEN
I am in GREEN and going to RED
I am in RED and going to GREEN
I am in GREEN and going to RED
I am in RED and going to GREEN
I am in GREEN and going to RED
I am in RED and going to GREEN
I am in GREEN and going to RED

This is a simple example but is useful for general understanding of Akka FSM actors. There are excellent use cases for FSM’s for example throttling messages. For more detailed introduction please also visit awesome Akka FSM documentation.

Written by Meetu Maltiar

August 1, 2013 at 08:50

Posted in Akka

Tagged with , ,

Simple Data Structures In Scala

leave a comment »


This session was presented at Knoldus knolx session. We went about discussing data structures. I talked about simple data structures like Queue and Binary Search Tree and their possible implementation in Scala. The idea was to know about a bit of Functional data structures and their implementation in Scala. I then discussed Binary Search Trees and their traversals.

Here is the presentation.

Written by Meetu Maltiar

December 5, 2012 at 11:17

Posted in Scala

Tagged with ,

Working With Elasticsearch In Scala

leave a comment »


Elasticsearch is an open-source, restful, distributed, search engine built on top of apache-lucene. You can read it more on their website.

We have an application built in scala with sbt as our build tool. Now we required to have a search capability on the output created by the application. We chose to use elasticsearch for our application.

In this post, we will learn to use elasticsearch java api in Scala. The scenario will be that we will index a json to elasticsearch. Then search the json document in elasticsearch in order to validate that it got indexed.

Let’s start by installing it. Installing Elasicsearch is simple, download it from link and unzip it. To run elasticsearch descend to unzipped directory and execute:

elasticsearch -f

“-f” tells elasticsearch to run in foreground. So, we will be able to see logs here.

Here is how it appears when it runs in foreground.

Read the rest of this entry »

Written by Meetu Maltiar

November 27, 2012 at 15:57

Posted in Scala

Tagged with ,

Knolx Session: Category Theory In Scala

leave a comment »


This session was presented at Knoldus knowledge session. There is a wonderful post on Category Theory by Debashish Ghosh. This presentation is inspired by his post here.

Here is the presentation.

Written by Meetu Maltiar

November 1, 2012 at 10:52

Posted in Scala

Tagged with ,

Knolx Sesion: Akka 2.0 Reloaded

leave a comment »


Akka allows us to write concurrent, fault tolerant and scalable applications. We recently migrated our product from Akka 1.3x to Akka 2.x. The new version is quite different from 1.3x versions. It is not merely an API change but an overall change. We have to also think differently to develop applications. This session was presented at Knolx Session at Knoldus. This talk gently introduces Akka 2.0 with simple and easy to run examples.

The presentation is inspired from Viktor Klang’s talk at NE Scala symposium.

Written by Meetu Maltiar

November 1, 2012 at 10:48

Posted in Akka, Scala

Tagged with ,

My Knolx Session: Introducing Scala

leave a comment »


This talk was given by me at Knoldus. At Knoldus we organize KnolX sessions so that our learning spreads in our organisation. This KnolX session had Scala flavor written all over it. We believe in experiential learning. This session has code examples which Knolders tried while I was explaining it.

I combined sbt, Scala, Scala collections and ScalaTest together in this presentation. The objective was that by the end of Knolx session we can create a project using SBT, write Scala code in it and finally test it. I made simple easy to understand examples which guys could play with.

Here is the presentation I gave. It has an assignment at the end which you can try.

Written by Meetu Maltiar

June 14, 2012 at 13:36

Posted in Scala

Tagged with , ,