Akka is an Actor model-based concurrency framework built on top of the JVM, improving the platform for building scalable, resilient and responsive concurrent applications. This paper is mainly about my understanding of the study and application of Akka.

The Actor model

Akka’s core is the Actor, the Actor, so have to say I popular Actor model, for example, assume that the reality of two people, they only know the address of the other party, they want to communicate, to pass information to the other party, but no mobile phone, telephone and other ways, such as network, so they can only use letters between the message, It is very similar to the postal system in the real world. If you want to send a letter, you only need to post it to the corresponding mailbox according to the address. You do not need to know how it helps you to process the delivery, and you may also receive the reply from the recipient, which is equivalent to message feedback. The letters in the example above are the equivalent of messages in actors, which communicate with each other only through messages. Of course, Actor model is more complex than this, here is mainly a concise explanation of the concept of Actor model.

Actors model in Akka

  • The concurrency model is abstracted at a higher level
  • Asynchronous, non-blocking, high-performance event-driven programming model
  • Lightweight event handling (1GB of memory can hold millions of actors)

Why is the Actor model a solution to concurrency problems?

At the beginning, I didn’t understand it very well. I always thought that how to deal with concurrent problems is how to ensure the consistency and correctness of shared data. Why is there such a problem of maintaining the correctness of shared data? But our program is multi-threaded, multiple threads to modify the same data, if not synchronized conditions, is bound to cause data pollution. So we can change the thinking and use a single thread to handle the corresponding request, but some people will ask, if single thread processing, how can the performance of the system. The emergence of the Actor model solves this problem.

Actor model overview:

The Actor model

When an Actor sends a message to another Actor, the message is in order. You only need to send the message to the corresponding mailbox. As for how the other Actor handles your message, you do not know, of course, you can also wait for its reply.

Actors in the JVM have the following characteristics:

  • Each Actor has a mailbox
  • Actors process messages serially
  • Messages in actors are immutable

It’s not clear from the descriptions above that actors have an advantage in dealing with concurrency.

But I’ve made two points: simplify concurrent programming and improve program performance

1. Simplify concurrent programming:

We initially said concurrent caused the biggest problem is to the operation of the Shared data, we in the face of concurrent problems more USES is with lock to ensure consistency of Shared data, but it will also bring other related issues, such as going to the granularity of the lock (the method, block, etc.), the lock in the form of (read lock, write locks, etc.), These problems are very important for concurrent programs, but a programmer who writes concurrent programs for the first time, often can not control very well, which undoubtedly increases the complexity of programming for programmers, and it is not easy to control, but the use of Actor does not lead to these problems, First of all, the message characteristics of actors feel that there will be no trouble in sharing data in communication with actors. In addition, messages are processed in serial in actors, which will not pollute the data in actors. Writing concurrent programs with actors will undoubtedly greatly reduce the complexity of coding.

2. Improve program performance:

So we talked about how do you guarantee performance if you’re using a single thread? First of all, the Actor is very lightweight, you can create many actors in the program, and the Actor is asynchronous, so how to use it this feature, we need to do is take the corresponding concurrent events as much as possible, divided into small, let each Actor to deal with the corresponding small events, fully to take advantage of its characteristics of asynchronous To improve the performance of the program.

In fact, native actors in Scala don’t do a lot of things. They are not a complete concurrency solution and are not suitable for production environments such as error recovery and state persistence, so the Akka package has replaced native actors in newer versions of Scala class libraries.

Akka

That let’s simply say Akka, Akka concurrent solution as a set of mature, are being used by a lot of industry, especially in the financial, games, and other fields, the fault-tolerant mechanism in the Akka, persistence, remote call, the log is important modules, such as the content will be in the subsequent articles in this series, to explain in detail. Let’s end this article with an introductory Akka program. Now let’s say we have a household robot, and all we need to do is send it a message and it will do it for us. Now let’s simulate this scenario with a program: source link

This example uses Scala, the construction tool is SBT, and the IDE is IntelliJ IDEA.

1. First create a Scala project based on SBT

Build the SBT configuration:

name := "Example_01"

version := "1.0"

scalaVersion := "2.11.8"

val akkaVersion   = "2.4.16"

libraryDependencies +=
  "com.typesafe.akka"% %"akka-actor" % akkaVersionCopy the code

2. Let’s define some messages:

trait Action{
  val message: String
  val time: Int
}

case class TurnOnLight(time: Int) extends Action {   // Turn on the light message
  val message = "Turn on the living room light"
}

case class BoilWater(time: Int) extends Action {   // Boil water message
  val message = "Burn a pot of water"
}Copy the code

3. We use Actor to realize a simulated robot:

class RobotActor extends Actor {
  val log = Logging(context.system, this)
  def receive: Receive = { // The robot accepts the command
    case t: TurnOnLight => log.info(s"${t.message} after ${t.time} hour")
    case b: BoilWater => log.info(s"${b.message} after ${b.time} hour")
    case _ => log.info("I can not handle this message")}}Copy the code

4. Let’s test the robot:

object Example_01 extends App {
  val actorSyatem = ActorSystem("robot-system") 
  val robotActor = actorSyatem.actorOf(Props(new RobotActor()), "robotActor") // Create a robot
  robotActor ! TurnOnLight(1) // Send a light on command to the robot
  robotActor ! BoilWater(2) // Send a boil water command to the robot
  robotActor ! "who are you" // Send an arbitrary command to the robot
  actorSyatem terminate ()
}Copy the code

5. Running result

[INFO] [03/19/2017 13:48:05.622] [robot-system-akka.actor. Default-dispatcher-4] [akka://robot-system/user/robotActor] Turn on the living room light after 1 hour [INFO] [03/19/2017 13:48:05.622] [robot-system-akka.actor.default-dispatcher-4] [akka://robot-system/user/robotActor] Burn a pot of water after 2 hour [INFO] [03/19/2017 13:48:05.622] [robot-system-akka.actor. Default-dispatcher-4] [akka://robot-system/user/robotActor] I can not handle this messageCopy the code

Above is a very simple example of Akka. We first created an Actor of a robot, and then sent it different instructions to do the corresponding things according to the instructions. You can try to write a similar example yourself.

This is the end of the article, the next chapter will mainly tell you about the hierarchical structure of actors in Akka.