11: ♥ Coding Scala Way – Actors with Akka – part 1

We already saw in Java: Producer and Consumer Java Multi-threading code. This extends the tutorial “Simple Akka tutorial in Scala step by step” for setting up the environment with right plugins and libraries with Eclipse & Maven.

The Akka Actors sending & receiving messages

Akka Actors conceptually each have their own light-weight thread. Actors are represented to the outside using ActorRefs, which are objects that can be passed around freely and without restriction. The “!” method is in the “akka.actor.ActorRef” trait.

Let’s look at a very simple example of sending a message to an actor.

Output:

As you can see there are two threads involved. The JVM “main” thread, the consuming actor thread “producer-consumer-akka.actor.default-dispatcher-2 “.

!” is a method that sends (tells) a message to a consumer. Once the message has been delivered to the actor, the actor processes the message by invoking its receive method.

Alternatively, use “tell” method

The “tell” method is in the “akka.actor.ScalaActorRef” trait.

Here is the Scala code in action.

The messages don’t have to be of type String

Output:

What if you want to spawn a new producer thread instead of the default JVM main thread

Output

Shutting down or stopping Akka system

Instead of System.exit(1), you can shutdown with

In order to close an actor, you can do

Print Friendly
The following two tabs change content below.
Arulkumaran Kumaraswamipillai
Mechanical Engineering to Java freelancer since 2003. Published Java/JEE books via Amazon.com in 2005, and sold 35K+ copies. Books are outdated and replaced with this online Java training. join my LinkedIn group.
Arulkumaran Kumaraswamipillai

Mechanical Engineering to Java freelancer since 2003. Published Java/JEE books via Amazon.com in 2005, and sold 35K+ copies. Books are outdated and replaced with this online Java training. join my LinkedIn group.

Posted in Scala way of coding

800+ Interview Q&As with lots of diagrams & code ♥Free | ♦FAQs | Hover/Slide for full text

open all | close all

200+ Java Interview FAQs – Quick Prep

open all | close all

16 Java Key Areas to be a top-notch

open all | close all

80+ Java Tutorials – Step by step

open all | close all

100+ Java Coding Exercises

open all | close all

How good are your

open all | close all