Anatomy of an actor

Before diving into a full-blown application, let's look at the different components of the actor framework and how they fit together:

  • Mailbox: A mailbox is basically a queue. Each actor has its own mailbox. When you send a message to an actor, the message lands in its mailbox and does nothing until the actor takes it off the queue and passes it through its receive method.
  • Messages: Messages make synchronization between actors possible. A message can have any type with the sole requirement that it should be immutable. In general, it is better to use case classes or case objects to gain the compiler's help in checking message types.
  • Actor reference: When we create an actor using val echo1 = system.actorOf(Props[EchoActor]), echo1 has type ActorRef. An ActorRef is a proxy for an actor and is what the rest of the world interacts with: when you send a message, you send it to the ActorRef, not to the actor directly. In fact, you can never obtain a handle to an actor directly in Akka. An actor can obtain an ActorRef for itself using the .self method.
  • Actor context: Each actor has a context attribute through which you can access methods to create or access other actors and find information about the outside world. We have already seen how to create new actors with context.actorOf(props). We can also obtain a reference to an actor's parent through context.parent. An actor can also stop another actor with context.stop(actorRef), where actorRef is a reference to the actor that we want to stop.
  • Dispatcher: The dispatcher is the machine that actually executes the code in an actor. The default dispatcher uses a fork/join thread pool. Akka lets us use different dispatchers for different actors. Tweaking the dispatcher can be useful to optimize the performance and give priority to certain actors. The dispatcher that an actor runs on is accessible through context.dispatcher. Dispatchers implement the ExecutionContext interface so they can be used to run futures.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.164.34