Scala and Akka: An Introduction

Scala is easily my favorite programming language.  It manages seamlessly to integrate a rich object-oriented paradigm with most (if not all) of the features one would expect from a functional language.  Today, I started learning about Akka, which is (as described by its website), “a toolkit for building highly concurrent, distributed, and resilient message-driven applications for Java and Scala.”

Inspired by Erlang’s actor-based concurrency, Akka solves many of the problems associated with multithreaded programming on the JVM.  For a very brief example of how Akka works, let’s consider the scenario of a counter that we want to be able to increment and decrement in a parallel environment.

First, let’s go ahead and import Akka and create an ActorSystem for our application:

import akka.actor._

val system = ActorSystem("counterDemo")

Second, we declare a companion object to our soon-to-be Counter actor, which holds the messages we’ll be able to send.

object Counter {
  case object Increment
  case object Decrement
  case object Print
}

With that in place, we can now declare our Counter actor:

class Counter extends Actor {
  import Counter._

  var count = 0

  def receive: Receive = {
    case Increment => count += 1
    case Decrement => count -= 1
    case Print => println(s"[counter] My current count is $count")
  }
}

Notice that the Counter class extends from akka.actor.Actor and imports the messages from the companion object.  Then, the class declares a mutable piece of state data, i.e., the count.  Finally, the class implements the required method receive.  The receive method is actually a partial function from Any to Unit, which specifies what the actor should do when a particular message is received.

To use our new counter application, we can import the messages from the companion object into scope.  Next, we register the counter actor with the actor system previously declared.  Then, using the ! infix method (read: “tell”), we can tell the actor to increment five times, decrement three times, and print the count.

import Counter._

val counter = system.actorOf(Props[Counter], "myCounter")

(1 to 5).foreach(_ => counter ! Increment)
(1 to 3).foreach(_ => counter ! Decrement)
counter ! Print

After running this application, the following is printed to the console, as expected:

[counter] My current count is 2

This is a very interesting way of thinking about programming.  Instead of calling methods on objects, we are sending messages to actors.  The question I have now, though, is how are we sure we will get 2 every time in the above example?  Said differently, how are we sure the Print message is executed last, given that messages are sent asynchronously?  I will soon find out as I continue to learn about this impressive framework.

[UPDATE] Well, I have learned that Akka guarantees that if message A is sent before message B, message A will, indeed, be processed first.  The way this works — with a pool of threads — is quite fascinating.  In any event, please check out the gist below, which implements a simple voting system in Scala with Akka to demonstrate how we can change an actor’s behavior.

Gist: Simple Voting System

Goroutines

As I mention in my first post, I am learning a bit of Go. Today, I came across goroutines, which are essentially functions or methods that run concurrently, in a “thread”-like way.

So if we have the (very basic) code:

func main() {
   go makeSureBothStatementsGetInThere()
   fmt.Println("We are executed concurrently.")
}

func makeSureBothStatementsGetInThere() {
   fmt.Println("We are executed concurrently.")
}

what will happen is that go will invoke makeSureBothStatementsGetInThere() concurrently with the fmt.Println statement below it. Thus, it is possible to have one statement print to the screen or both statements print to the screen. We won’t know in advance.

That’s where channels come in:

func main() {
   quitSignal := make(chan bool)

   go makeSureBothStatementsGetInThere(quitSignal)
   fmt.Println("We are executed concurrently.")
   <-quitSignal
}

func makeSureBothStatementsGetInThere(channel chan bool) {
   fmt.Println("We are executed concurrently.")
   channel <- true
}

Now the program will await the quitSignal before exiting, ensuring both statements are printed to the screen.

I think this is a pretty simple way to do a very complicated task (i.e., threading, essentially). Go seems kinda neat.

[UPDATE] I’ve delved a bit deeper into goroutines, and I’ve learned a design pattern, which seems to be incredibly useful in Go application design. Suppose you have a lot of code in an application, which you want to run concurrently with the rest of your application. One way to do it would be to use a “goroutine generator.”

We define a function waitThenSend():

func waitThenSend(i, value int) chan int {
   channel := make(chan int)

   go func() {
      time.Sleep(time.Duration(i) * time.Second)
      channel <- value
   }()

   return channel
}

This can be called in our main() function, like so:

func main() {
   fmt.Println(<-waitThenSend(3, 42))
}

What will happen? The program will wait for three seconds, and then it will print out the integer 42. By using this pattern, we can put any code we want to run concurrently inside the generator function’s goroutine and then simply call the generator function when needed.

Very interesting and, I’m sure, incredibly useful.

Welcome Aboard

I’m an attorney licensed to practice in three U.S. states, and, as my (pretty big) hobby, I am learning to program. I’ll first talk about some of my experience with coding, and then I’ll talk about the purposes of this blog.

I learned HTML and very basic CSS probably sometime in middle school, and I was playing with computers from an exceedingly young age. When I got to college, I kind of lost interest in the subject. But in recent years, the interest has come back. Fiercely. At first, I focused on JavaScript, learning it pretty much in-and-out on both the front-end (React and Angular.js) and the back-end (Node.js).

More recently, I have been learning more and more of other languages. Lately, I’ve been focusing heavily on Java, Scala, and C++. At the same time, I am dabbling in Go, and even a little bit of Elixir here and there.  The purpose of this blog is so that I can share interesting discoveries with whomever is interested in reading about them.

Please check out my projects on GitHub.

I can be reached by e-mail at brehardev@gmail.com.

Thanks for joining me.