Actors
Describes the XOOM platform Reactive foundation and demonstrates how it is used.

Actor Model Foundation

In 1973, Dr. Carl Hewitt and his colleagues formulated the Actor Model. In recent years, the inventor of object orientation, Alan Kay, has stated that the Actor Model retained more of what he thought were the important object ideas. So, when you think of the Actor Model, think of objects done right.
A Resource actor sending a command message to a Model Entity actor.
The XOOM Actors toolkit is an implementation of the Actor Model, and all primary platform components are built on our Actor Model implementation. Read on for detailed information on the use of XOOM Actors.

What Are Actors?

XOOM Actors is an implementation of the Actor Model. The ideas behind the Actor Model are pretty simple, and these points show how XOOM Actors implement it.
  1. 1.
    The basic unit of computation is expressed through actors. Actors are basically objects, but their behaviors are requested by sending messages asynchronously rather than through directly invoking their methods. This enables all communication between actors to be performed through asynchronous messaging passing. Determined by a scheduler, each actor that has been sent a message will be given the opportunity to receive and process it, which also happens asynchronously.
  2. 2.
    Actors can create other actors. As Carl Hewitt is known to say, “One actor is no actors. Actors come in systems.” Thus, your applications should use not just some actors, but many actors. Understand that once you start down the road of asynchronous behaviors, you are all in. Just as you don’t kind of go swimming, because you are either completely wet, or you are not, you don't kind of use actors. If you try to fight the asynchrony, you will experience pain and software with very strange bugs.
  3. 3.
    Each actor can designate the behavior it will exhibit for the next message it receives. This is roughly the State pattern. Any actor using the XOOM Actors toolkit can dynamically become another kind of actor in preparation for handling its current state and any subsequent messages.
  4. 4.
    What is most unique about the XOOM Actors implementation is type safety by design, and the simplicity with which is it implemented and consumed. All that a programmer needs to understand is interfaces and implementation classes, and they get the asynchrony for free.
  5. 5.
    Most other actor implementations use a receive method or code block that takes Object (or Any) as a parameter. Thus, the receive needs to determine which messages to accept and which ones are not permitted at any given time; this may be especially necessary when the actor designates its next behavior (it becomes another type of actor). Also what is unique about XOOM Actors is that the current designated behavior can be based on a different interface that is implemented by the actor. In other words, any one actor can implement multiple interfaces and receive messages for any given interface when it chooses to.
  6. 6.
    Most modern actor model implementations use mailboxes to deliver messages. Each actor has a mailbox where messages are received into a FIFO queue, and each message is processed one at a time on an available thread. This is true for XOOM Actors, yet there are special kinds of mailboxes that have certain advantages (and possibly disadvantages).
  7. 7.
    You can tune your actor’s world and stage to support any number of threads, but it’s best to limit this number based on the available number of processor hyper-threaded cores, or a bit more. Fundamentally, you can’t run more threads simultaneously than there are available cores, e.g. Runtime.getRuntime().availableProcessors().
Using objects in a typical fashion, such as with Java or C#, we have become accustomed, even addicted, to a blocking paradigm.
A Client object invoking a method on a Server object, which blocks the Client.
Here a Client object invokes a method on a Server object. Understand that this is an in-process (in-VM) invocation, not a remote client and a remote server. The point is, when a method invocation occurs, the Client is blocked until the Server returns from the method invocation. In contrast, the Actor Model works differently.
The Actor Model is message-driven and processes messages asynchronously.
When the Sender actor wants another actor to provide a service, it sends that actor a message. The message is sent to the Receiver actor and handled asynchronously, but not until a thread is available. The Sender continues moving forward with its current activities, and when completed returns from its own message handling.
As previously stated, with the various Actor Model implementations (e.g. Erlang and Elixir), neither messages or the message receiver are strongly typed. Yet, with XOOM Actors type-safe messages are the fundamental building block, not an experimental afterthought. A strongly-typed Actor Model implementation is important at this time when type safety is in high demand and can provide much more reliable systems.
With its careful but simple design, XOOM Actors are a great foundation on which to build the other tools in the XOOM platform.

How Do Actors Work?

Actors collaborate by sending messages, one actor to another. When there are hundreds, thousands, or millions of actors, there are many actors sending messages simultaneously. Still, any one actor can send only one message to one other actor at a time. Following that, the same actor can send a message to the same actor or a different actor. This fulfills the first point of the following description of the actor message-receiving contract.
An actor is a computational entity that, in response to a message it receives, can concurrently:
  • send a finite number of messages to other actors;
  • create a finite number of new actors;
  • designate the behavior to be used for the next message it receives.
There is no assumed sequence to the above actions and they could be carried out in parallel.
Actors also must be able to fulfill the second and third points: actors can create child actors, and actors can prepare themselves for subsequent message receipt.

Actors in Action

Now consider a brief tutorial on XOOM Actors. This tutorial takes you through preparing your build environment and also how to implement two actors that collaborate to accomplish a goal.
To get started, create your own playground project to work with. You can name this project playground. If you use Maven, place a dependency into your playground’s pom.xml file.
1
...
2
<dependencies>
3
<dependency>
4
<groupId>io.vlingo.xoom</groupId>
5
<artifactId>xoom-actors</artifactId>
6
<version>x.y.z</version>
7
</dependency>
8
</dependencies>
9
...
Copied!
If you prefer Gradle, insert the following into your build.gradle.
1
dependencies {
2
compile 'io.vlingo.xoom:xoom-actors:x.y.z'
3
}
4
5
repositories {
6
jcenter()
7
}
Copied!
The x.y.z is a semantic version number and reflects the version of xoom-actors JAR file that you depend on. This number may be something such as 1.8.0. You will find the available versions, including the most recent version, available on one of the supported public repositories.
Additionally, add a JUnit dependency into your build script since the tutorial uses JUnit to run the actor collaboration.
1
...
2
<dependencies>
3
<dependency>
4
<groupId>junit</groupId>
5
<artifactId>junit</artifactId>
6
<version>4.12</version>
7
<scope>test</scope>
8
</dependency>
9
</dependencies>
10
...
Copied!
Or if using Gradle:
1
dependencies {
2
compile 'junit:junit:4.11'
3
}
Copied!
Although there are a few different ways to configure the XOOM Actors runtime environment, we will skip that step here. It's easier to start with reasonable defaults instead. The configuration approaches are presented later.
Without delay, consider the really fun part—the programming. You are going to create a really basic Ping Pong game.
The Pinger and Ponger send message to and receive messages from each other.
You need to create a few Java interfaces and classes. There’s a Java interface that acts as the type safe messaging protocol of the first actor that you will create. For now, create a Pinger interface with a single method definition, named ping(), which takes a Ponger as a parameter.
1
package playground;
2
3
import io.vlingo.xoom.actors.Stoppable;
4
5
public interface Pinger extends Stoppable {
6
void ping(final Ponger ponger);
7
}
Copied!
Next create a Ponger interface the same way, but with a pong() method that takes a Pinger as a parameter.
1
package playground;
2
3
import io.vlingo.xoom.actors.Stoppable;
4
5
public interface Ponger extends Stoppable {
6
void pong(final Pinger pinger);
7
}
Copied!
Now you have two protocols or two different actors. These define the type-safe behaviors that one or more actors will implement, and the means by which clients will interact with the actors. In case it’s not obvious, Pinger is a client of Ponger, and Ponger is a client of Pinger.
It’s time to create two simple actors. First create one to implement the Pinger protocol.
1
package playground;
2
3
import io.vlingo.xoom.actors.Actor;
4
5
public class PingerActor extends Actor implements Pinger {
6
private final Pinger self;
7
8
public PingerActor() {
9
self = selfAs(Pinger.class);
10
}
11
12
public void ping(final Ponger ponger) {
13
ponger.pong(self);
14
}
15
}
Copied!
After that, create another actor to implement the Ponger protocol.
1
package playground;
2
3
import io.vlingo.xoom.actors.Actor;
4
5
public class PongerActor extends Actor implements Ponger {
6
private final Ponger self;
7
8
public PongerActor() {
9
self = selfAs(Ponger.class);
10
}
11
12
public void pong(final Pinger pinger) {
13
pinger.ping(self);
14
}
15
}
Copied!
You now have two actors that collaborate to play ping pong. The problem is that these actors will play ping pong nonstop, forever, unless we do something to prevent that. Doing so demonstrates how actors can maintain their own state, just like typical objects.
1
package playground;
2
3
import io.vlingo.xoom.actors.Actor;
4
5
public class PingerActor extends Actor implements Pinger {
6
private int count;
7
private final Pinger self;
8
9
public PingerActor() {
10
count = 0;
11
self = selfAs(Pinger.class);
12
}
13
14
public void ping(final Ponger ponger) {
15
if (++count >= 10) {
16
self.stop();
17
ponger.stop();
18
} else {
19
ponger.pong(self);
20
}
21
}
22
}
Copied!
Looking back at the Pinger and Ponger interface definitions, you will notice that both of these protocols extend the Stoppable protocol. Thus, they can both be stopped by other actors that have a Stoppable reference to them. We use that capability from within PingerActor to cause both actors to stop when the count reaches 10.
Note that in this case the actors are not required to implement their own stop() methods. That’s because the abstract base class, Actor, implements stop() for them. You could override stop() to find out when your actor is being stopped, but that’s not necessarily a good idea. What if you forgot to invoke the super’s stop()? That would make you think that your actor was going to stop, but the actor would never shut down because the Actor base class behavior would never be run. If you want to know when you are being stopped, you can override one of the four life cycle methods instead of stop().
1
package playground;
2
3
import io.vlingo.xoom.actors.Actor;
4
5
public class PingerActor extends Actor implements Pinger {
6
private int count;
7
private final Pinger self;
8
9
public PingerActor() {
10
count = 0;
11
self = selfAs(Pinger.class);
12
}
13
14
public void ping(final Ponger ponger) {
15
if (++count >= 10) {
16
self.stop();
17
ponger.stop();
18
} else {
19
ponger.pong(self);
20
}
21
}
22
23
@Override
24
protected void afterStop() {
25
logger().log("Pinger " + address() + " just stopped!");
26
super.afterStop();
27
}
28
}
Copied!
All five life cycle methods are:
  • beforeStart()
  • afterStop()
  • beforeRestart(final Throwable reason)
  • afterRestart(final Throwable reason)
  • beforeResume(final Throwable reason)
These enable you to see when significant life cycle events occur with your actor. The restart life cycle methods are related to actor supervision. When your actor’s supervisor sees your actor failed with an Exception, it can take a number of actions. Your supervisor can tell your actor to resume, to stop, or to restart. If it tells your actor to resume, the beforeResume() is invoked. When it tells your actor to restart, the beforeRestart() is invoked first, and then the afterRestart() is invoked. Since your actor has failed, it may have been left in an invalid state. In such cases, these three life cycle methods give your actor the opportunity to clean up after the problem that caused the Exception and also reinitialize itself before reacting to its next available protocol message.
The Exception recovery methods DO NOT cause the Actor instance to be completely discarded and recreated. Therefore, it is the responsibility of the Actor to set its state to a safe point before message processing resumes.
The above afterStop() method shows two additional perks of XOOM Actors. All actors have a personal address, which is available through your inherited address() method. Also, all actors have a Logger available via its logger() method. Any information that you log will be output asynchronously through a registered Logger actor, so your actor won't block while file output is performed.
Alright, we have two actors, but how do we bring the actors to life in the first place, and how do we get them to start collaborating in game play? Here’s how you start up the World for your actors to play in.
1
package playground;
2
3
import org.junit.Test;
4
5
import io.vlingo.xoom.actors.Definition;
6
import io.vlingo.xoom.actors.World;
7
8
public class PlaygroundTest {
9
10
@Test
11
public void testPlayPingPong() {
12
final World world = World.startWithDefaults("playground");
13
final Pinger pinger = world.actorFor(Pinger.class, PingerActor.class);
14
final Ponger ponger = world.actorFor(Ponger.class, PongerActor.class);
15
16
pinger.ping(ponger);
17
18
pauseThisThread();
19
20
world.terminate();
21
}
22
}
Copied!
When this test is run, a World is created. The World is a major component of XOOM Actors. In a nutshell, a World is the primary container within which actors live and play. Generally you would create only one World per service instance. In DDD terms, a World is the root of a Bounded Context. (Don't worry about the use of pauseThisThread(); it is explained below.)
After the World is started, two actors are created, and a reference to their respective protocol is returned. Each actor is created by passing its protocol and the concrete actor type. You may also create actors by means of a Definition. The Definition indicates the class of the actor that implements the protocol, such as PingerActor.class, which implements the Pinger.class protocol. There are four ways to instantiate an actor by means of its constructor:
  • Design the actor with a zero-parameter constructor, which is the case in the above example.
  • Pass the implementation class type as the second parameter to actorFor() as seen above, and also pass each constructor parameter following the implementation class type. This has the advantage of making the parameters visible, but they are passed as varargs each of type Object, and are thus not type-safe.
  • Create and pass a Definition object as the second parameter to actorFor(). The Definition contains the class of the actor implementation and a possibly one or more constructor parameters, or it can pass Definition.NoParameters. See the next code example for how to pass constructor parameters. This approach is also not type safe.
  • All three of the above actor instantiation options use reflection to call the actor's constructor. Use of reflection can be avoided and at the same time also provide absolute type-safe constructor parameters. To accomplish this, implement a factory for your various actor types using theActorInstantiator, a functional interface included in the xoom-actors SDK and runtime. Construct your specific ActorInstantiator type, pass any actor constructor parameters into the ActorInstantiator constructor. When the actor is ready to be created by the runtime, the ActorInstantiator method blah will be called. At that time call the specific actor's constructor when using new. (See example provided below.)
With these options available, consider the following (non-working) example of the PingerActor taking two parameters, a String and an int, using the Definition approach:
1
final Pinger pinger = world.actorFor(
2
Pinger.class,
3
Definition.has(
4
PingerActor.class,
5
Definition.parameters("Hey, yo!", 42),
6
"name-that-actor"));
Copied!
The simplest way to create an actor with constructor parameters is by means of the following shorthand method, but with the downside that the parameters are not checked for type safety by the compiler but instead at runtime when matching parameter types to a specific constructor:
1
final Pinger pinger = world.actorFor(Pinger.class, PingerActor.class, "Hey, yo!", 42);
Copied!
The following example employs a type-safe ActorInstantiator, which does not require the use of reflection:
1
public class PingerInstantiator implements ActorInstantiator<PingerActor> {
2
private final String message;
3
private final int value;
4
5
public ProtocolInstantiator(final String message, final int value) {
6
this.message = message;
7
this.value = value;
8
}
9
10
@Override
11
public ProtocolActor instantiate() {
12
return new PingerActor(message, value);
13
}
14
15
@Override
16
public Class<PingerActor> type() {
17
return PingerActor.class;
18
}
19
}
Copied!
There are three ways to use the PingerInstantiator, each of which is demonstrated separately in the follow example:
1
// Pass in a Definition
2
final PingerInstantiator instantiator = new PingerInstantiator("Hey, Yo!", 42);
3
final Pinger pinger = world.actorFor(Pinger.class, Definition.has(PingerActor.class, instantiator));
4
5
6
// Pass directly as an ActorInstantiator
7
final Pinger pinger = world.actorFor(Pinger.class, PingerActor.class, new PingerInstantiator("Hey, Yo!", 42));
8
9
// Use the FunctionalInterface for lazy instantiation
10
final Pinger pinger = world.actorFor(Pinger.class, () -> new PingerInstantiator("Hey, Yo!", 42));
Copied!
Look over the XOOM Actors source code repository for the several different ways that an actor can be created, including with a specific parent, a non-default logger, and a specialized supervisor.
One additional point about the unit test is appropriate. As you probably noticed, a method named pauseThisThread() is used.
1
...
2
private void pauseThisThread() {
3
try { Thread.sleep(100); } catch (Exception e) { }
4
}
5
...
Copied!
Some sort of coordination is necessary because the actors send and receive all protocol messages asynchronously. Recall that there will be a total of 10 pings. Since the messages are all delivered and reacted to asynchronously, there is no “automatic” way to know when all the messages, including the stop() for both actors, have been delivered.
Don't use Thread.sleep()in your tests or your production services.
Even so, this particular sleep approach is not correct, because on different machines a given sleep time may be insufficient for all messages to process. It's actually guess work to try to get this right. Additionally, if you configure a long-enough sleep time that will work for every possible machine and process load, it's going to make your tests slow on very fast machines and environments. So, one reason for showing you this in the example is to emphasize that you should not use thread sleeps.
The following shows how you can more conveniently test actors without using the thread sleep artifice. It uses the io.vlingo.xoom.actors.testkit.TestUntil component. This example also demonstrates how actors take constructor parameters. In the test method, create an instance of the TestUntil to pass to the PingerActor constructor.
1
public class PlaygroundTest {
2
3
@Test
4
public void testPlayPingPong() {
5
final World world = World.start("playground");
6
final TestUntil until = TestUntil.happenings(1);
7
final Pinger pinger = world.actorFor(Pinger.class, Definition.has(PingerActor.class, Definition.parameters(until)));
8
final Ponger ponger = world.actorFor(Ponger.class, Definition.has(PongerActor.class, Definition.NoParameters));
9
10
pinger.ping(ponger);
11
12
until.completes();
13
14
world.terminate();
15
}
16
}
Copied!
Then refactor PingerActor to take a TestUntil instance as a constructor parameter.
Using the Proxy Protocol
Note that the above test is provided with Pinger and Ponger instances. These are not direct references to the underlying PingerActor and PongerActor instances, but are instead proxies. Invoking a method on a proxy causes a message to be created and enqueued for the actor that backs the proxy.
Every such proxy implements a Proxy type. This can be used to access the Address of the actor using address(). In addition, all proxies supports working equals(), hashCode(), and toString() implementations.
Since the Proxy interface is not available by way of the Pinger protocol (or any other actor protocols), there is a way to obtain the Proxy instance:
final Address address = Proxy.from(pinger).address();
The Proxy type is available in the io.vlingo.xoom.actors package.
Additionally, the PingerActor must cause a happened() in its afterStop() method to signal to the test that the Pinger has stopped:
1
public class PingerActor extends Actor implements Pinger {
2
private int count;
3
private final Pinger self;
4
private final TestUntil until;
5
6
public PingerActor(final TestUntil until) {
7
this.until = until;
8
this.count = 0;
9
this.self = selfAs(Pinger.class);
10
}
11
...
12
@Override
13
protected void afterStop() {
14
logger().log("Pinger " + address() + " just stopped!");
15
until.happened();
16
super.afterStop();
17
}
18
}
Copied!
Before the afterStop() method causes the until.happened() the test method will block. As soon as the until.happened() causes its state to transition from 1 to 0, the test will unblock and the World will terminate. This enables the test to complete.
Don't use TestUntil in code that will be used in production.
Although passing a test construct into a production-quality actor is poor design choice, this example is only to show you that there are very reliable ways to test actors in an asynchronous messaging environment. Later you will see much better uses of TestUntil and other io.vlingo.xoom.actors.testkit tools.
In order to make the ping pong playground produce some output, create some log output in the ping() and pong() methods.
1
// in Pinger
2
...
3
public void ping(final Ponger ponger) {
4
++count;
5
logger().log("ping " + count);
6
if (count >= 10) {
7
self.stop();
8
ponger.stop();
9
} else {
10
ponger.pong(self);
11
}
12
}
13
...
14
15
// in Ponger
16
public void pong(final Pinger pinger) {
17
logger().log("pong");
18
pinger.ping(self);
19
}
20
...
Copied!
When the test is run, you will see the following output.
1
vlingo/actors(test): ping 1
2
vlingo/actors(test): pong
3
vlingo/actors(test): ping 2
4
vlingo/actors(test): pong
5
vlingo/actors(test): ping 3
6
vlingo/actors(test): pong
7
vlingo/actors(test): ping 4
8
vlingo/actors(test): pong
9
vlingo/actors(test): ping 5
10
vlingo/actors(test): pong
11
vlingo/actors(test): ping 6
12
vlingo/actors(test): pong
13
vlingo/actors(test): ping 7
14
vlingo/actors(test): pong
15
vlingo/actors(test): ping 8
16
vlingo/actors(test): pong
17
vlingo/actors(test): ping 9
18
vlingo/actors(test): pong
19
vlingo/actors(test): ping 10
Copied!
You can find an implementation of this tutorial code in the xoom-examples repository.
Now that this tutorial has given you some of the most import knowledge about XOOM Actors, you are ready to take a deeper dive into more details about the other facilities provided by XOOM Actors.

API

This section provides a how-to for the XOOM Actors toolkit API. The details are covered in sections. Some of these details are already demonstrated in the previous sections, including the tutorial.
An integral component used to manage asynchronous behaviors provided by actors is the Completes<T> protocol with its backing implementation. Being cited in this chapter and others, it's best to understand how it works. To do so, refer to our discussion provided in the Completes<T> documentation.

Starting and Terminating the Actor Runtime

To start up the XOOM Actors runtime you start the World object as follows.
1
final World world = World.startWithDefaults("my-world");
Copied!
This starts a World with normal runtime defaults in which Actor instances are created and run. For many uses of XOOM Actors the defaults are the easiest and safest way to use the Actorruntime.
The XOOM Actors World contains components that manage the reactive runtime.
There are a few different ways to start a World. The following is a summary.
Use this API when you want to start a World by loading configurations from the file named xoom-actors.properties. The name is used to name the World instance.
1
public static World start(final String name)
Copied!
The following API is used when you want to start a World with your own name-value pairs using java.util.Properties defined in code. The details of the xoom-actors.properties file are discussed below.
1
public static World start(final String name, final java.util.Properties properties)
Copied!
A World can be started using fluent configuration.
1
public static World start(final String name, final Configuration configuration)
Copied!
The details of programatic Configuration are discussed below.
When you are preparing to shut down your application or service that is using the World, you should use the following to terminate the Actor runtime.
1
world.terminate();
Copied!
The World::terminate() method is currently a synchronous operation, but in the future will become asynchronous. When the World terminates asynchronously there will be a Completes<T> or callback construct to inform the client when the termination has completed.

Using the xoom-actors.properties File

The Actor runtime may be configured by means of a file that adheres to the java.util.Properties conventions. Each property is defined by a name followed by = and then a value. For the XOOM Actors toolkit the file must be named xoom-actors.properties and be located in the runtime classpath. The following shows how the standard ConcurrentQueueMailbox can be defined in this properties file.
1
plugin.name.queueMailbox = true
2
plugin.queueMailbox.classname =\
3
io.vlingo.xoom.actors.plugin.mailbox.concurrentqueue.ConcurrentQueueMailboxPlugin
4
plugin.queueMailbox.defaultMailbox = true
5
plugin.queueMailbox.numberOfDispatchersFactor = 1.5
6
plugin.queueMailbox.dispatcherThrottlingCount = 1
Copied!
When defining properties in a properties file, long lines may be continued by placing an escape character of \ at the end of the line to be continued on the next line. To see example properties that can be used, you should review: xoom-actors/src/test/resources/xoom-actors.properties
Also the next subsection shows several configuration type objects and options.

Using Programmatic Configurations

As an alternative to using the file-based configuration, you can instead employ a configuration approach that provides a fluent API, an example of which follows.
1
final Configuration configuration =
2
Configuration
3
.define()
4
.with(PooledCompletesPluginConfiguration
5
.define()
6
.mailbox("queueMailbox")
7
.poolSize(10))
8
.with(SharedRingBufferMailboxPluginConfiguration
9
.define()
10
.ringSize(65535)
11
.fixedBackoff(2)
12
.dispatcherThrottlingCount(10))
13
.with(ManyToOneConcurrentArrayQueuePluginConfiguration
14
.define()
15
.ringSize(65535)
16
.fixedBackoff(2)
17
.dispatcherThrottlingCount(10)
18
.sendRetires(10))
19
.with(ConcurrentQueueMailboxPluginConfiguration
20
.define()
21
.defaultMailbox()
22
.numberOfDispatchersFactor(1.5f)
23
.dispatcherThrottlingCount(10))
24
.with(JDKLoggerPluginConfiguration
25
.define()
26
.defaultLogger()
27
.name("vlingo/actors(test)")
28
.handlerClass(DefaultHandler.class)
29
.handlerName("vlingo")
30
.handlerLevel("ALL"))
31
.with(CommonSupervisorsPluginConfiguration
32
.define()
33
.supervisor("default", "pingSupervisor", Ping.class, PingSupervisorActor.class)
34
.supervisor("default", "pongSupervisor", Pong.class, PongSupervisorActor.class))
35
.with(DefaultSupervisorOverridePluginConfiguration
36
.define()
37
.supervisor("default", "overrideSupervisor", DefaultSupervisorOverride.class))
38
.usingMainProxyGeneratedClassesPath("target/classes/")
39
.usingMainProxyGeneratedSourcesPath("target/generated-sources/")
40
.usingTestProxyGeneratedClassesPath("target/test-classes/")
41
.usingTestProxyGeneratedSourcesPath("target/generated-test-sources/");
Copied!
Follow the configuration definition it can be used to start the World instance.
1
final World world = World.start("my-world", configuration);
Copied!

World Miscellaneous Resources

In addition to the above facilities, a World provides the following. All concrete Actor instance may obtain both their Stage and their World instances as follows, which enables the Actor to reach specific facilities offered by each.
1
// inside an actor
2
final Configuration configuration = stage().world().configuration();
Copied!
You may require the use of the means to create unique Actor addresses or a way to produce an address from a primitive or String value. To do so, request it by means of the method addressFactory().
1
public AddressFactory addressFactory()
Copied!
You may obtain the immutable Configuration of the World runtime. Even if you load your runtime properties from the xoom-actors.properties or your own java.util.Properties definition, all of your runtime configurations are placed in the Configuration.
1
public Configuration configuration()
Copied!
All messages sent to Actor instances that cannot be delivered for any reasons, such as the Actor instance has previously been stopped, are delivered to the special Actor know as DeadLetters. You may subscribe to receive DeadLetters messages.
1
public DeadLetters deadLetters()
Copied!
Use the following DeadLetters protocol method to subscribe to its received messages. Your listener Actor must implement the DeadLettersListener protocol.
1
void registerListener(final DeadLettersListener listener)
Copied!
If you want to obtain the default Logger that is provided to all Actor instances, use the following method.
1
public Logger defaultLogger()
Copied!
Every top-level application- or service-created Actor is a child of the default parent Actor.
1
public Actor defaultParent()
Copied!
Every Actor must be assigned to a overarching supervisor. The following provides a reference to the default supervisor of all newly created Actor instance.
1
public Supervisor defaultSupervisor()
Copied!
Although the default Logger is available through the World interface, there may also be a number of named Logger instances. If you use non-default Logger instances, they may be obtained via the following World facility. All Logger instances obtained through the standard XOOM Actors plugins are backed by actors, and are thus asynchronous by default.
1
public Logger logger(final String name)
Copied!
The Logger implementation is based on SLF4J. You may configure your Logger to your standards. The following is a simple example that outputs strictly to the console.
1
<configuration>
2
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
3
<encoder>
4
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
5
</encoder>
6
</appender>
7
8
<root level="debug">
9
<appender-ref ref="STDOUT" />
10
</root>
11
</configuration>
Copied!
Another example logs to both the console and a file.
1
<configuration>
2
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
3
<file>myApp.log</file>
4
<encoder>
5
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
6
</encoder>
7
</appender>
8
9
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
10
<encoder>
11
<pattern>%msg%n</pattern>
12
</encoder>
13
</appender>
14
15
<root level="debug">
16
<appender-ref ref="FILE" />
17
<appender-ref ref="STDOUT" />
18
</root>
19
</configuration>
Copied!
There are many references available with far more details about the SLF4J facility. Note that one such configuration supports asynchronous log appending. You may or may not find that this enhances the asynchronous logging that already exists through the logging actor.
The Logger protocol provides several facilities for logging application/service output and exceptions.
1
void trace(String message)
2
void trace(String message, Object... args)
3
void trace(String message, final Throwable throwable)
4
5
void debug(String message)
6
void debug(String message, Object... args)
7
void debug(String message, final Throwable throwable)
8
9
void info(String message)
10
void info(String message, Object... args)
11
void info(String message, final Throwable throwable)
12
13
void warn(String message)
14
void warn(String message, Object... args)
15
void warn(String message, final Throwable throwable)
16
17
void error(String message)
18
void error(String message, Object... args)
19
void error(String message, final Throwable throwable)
Copied!
The World interface provides some additional facilities, but ones that are useful only for plugins. Those are documented below.

Creating Actors

Once you have started a World you are able to create Actor instance to run in it. As a reminder, there is nothing mysterious about actors. Actors are basically objects, but their behaviors are requested by sending messages asynchronously rather than through directly invoking their methods. The following shows you how to create an actor.
1
final Simple simple = world.actorFor(Simple.class, SimpleActor.class);
Copied!
In this example the World is used to create a new instance of the SimpleActor type. The SimpleActor type implements the protocol defined by the interface named Simple. Thus, actors provide protocol implementations, and they can implement multiple protocols.
In this example the SimpleActor takes no constructor parameters. If it did accept parameters then the parameters could be listed as follows.
1
final Simple simple = world.actorFor(Simple.class, SimpleActor.class, p1, p2, p3);
Copied!
The parameters must be listed in the order in which to constructor accepts them. In the above example the parameters are listed as p1, p2, and p3. These parameters could be of any type, and each parameter is required to follow the convention that the constructor contract requires.
When the World method actorFor() returns, the requesting client is given a reference to the protocol that provides asynchronous access to the Actor. This reference is used to send messages via methods on the protocol. The Simple protocol is defined as follows.
1
public interface Simple {
2
void simpleSay();
3
}
Copied!
There is a single method named simpleSay(). Messages are sent asynchronously to the concrete Actor instance, which in the case of the above example is an instance of SimpleActor. This behavior is demonstrated by the following expression.
1
simple.simpleSay();
Copied!
The fundamental behavior of a method invocation on the protocol reference is to reify the method invocation to a message that is sent asynchronously to the Actor. The reification is accomplished by creating a Function that represents the method invocation and enqueuing the Function instance on to the Actor's Mailbox. The Function will later be applied to the Actorinstance when all previously enqueued messages have been processed and a thread becomes available to process the message at the front of the Mailbox. Thus, the method invocation is temporally decoupled from the sending side and the receiving side.

A Stage for Actors

The World does not directly create an Actor. Instead, the World dispatches actorFor() requests to the default Stage. It is the Stage that provides the concrete implementation of actorFor().
A Stage is the abstraction within which Actor instances are maintained. A World has at least one Stage, which is known as the default Stage, and its name is "__defaultStage". If you need to query the instance of the default stage, you use the following World method.
public Stage stage()
Every Stage supports two important behaviors, actorFor() and actorOf(). The actorFor() is a creational method, and there are several overloads supporting various parameter options. Using the method various implementations of the method actorFor() will create a new Actor instance and answer one or more protocols. Once you have a reference to a protocol you are able to send messages to the given Actor that implements the protocol(s).
The actorOf() method has a different purpose. Given an existing Actor that is contained within a given Stage, you may use actorOf() to find the existing Actor by passing the Address of the Actor. The actorOf() answers a Completes<T> because it is an asynchronous operation, answering the requested protocol eventually.
An Actor may obtain its containing Stage and its World as follows.
1
// inside an actor
2
final Stage myStage = stage();
3
final World myWorld = myStage.world();
Copied!
You may create additional Stage instances within the World, but the default Stage is automatically provided when a World starts. The World default Stage is responsible for holding the private root actor and the public root actor. These two instances act as default supervisors, which are responsible for protecting a World from catastrophic failures. Supervision is explained in detail below.
Since the World must create some default operational Actor instances when it is started, it may be best to segregate your application/service Actor instances into another Stage. It's simple to accomplish, as seen here.
1
public Stage stageNamed(final String name)
Copied!
If the Stage instance with the given name does not yet exist, a new Stage with that name is created and returned.
We don't suggest creating several or many Stage instances. It's likely that the default Stage and one application/service Stage instance will be sufficient. Yet, we don't set a limit on the number of Stage instances in case more than two would be useful.

Scheduler and the Scheduled Protocol

Every Stage has its own Schedular, which may be used to produce time-lapsed events that are sent to an Actor.
1
// inside an actor
2
final DataPacket packet = new DataPacket(0);
3
stage().scheduler().schedule(selfAs(Scheduled.class), packet, 100, 1_000);
Copied!
An Actor can schedule itself or another Actor, such as one or more of its children, for some timed event notification. In other words, it need not pass itself as the Scheduled instance.
A concrete Actor scheduling itself for notifications must implement the Scheduled protocol in order for it to be scheduled to receiver interval signals.
The above example registers a repeating schedule that will begin within 100 milliseconds of the registration and will repeat every 1 second (1_000 milliseconds). The Actor scheduling itself for notifications must implement the Scheduled protocol, and it passes an Actor enabled reference to that effect using the runtime method selfAs(). The Actor can associate some specific data with which it will be notified on each event, which in this example is the DataPacket instance packet. This DataPacket type is only used for the example, and would be replaced with your own type, or you can pass null if the data is unused.
Similarly you can schedule a single notification. The interval will not not be repeated as in the above example.
1
// inside an actor
2
final DataPacket packet = new DataPacket(0);
3
stage().scheduler().scheduleOnce(selfAs(Scheduled.class), packet, 100, 1_000);
Copied!
When registering a Scheduled object you are provided a Cancellable instance. You may use this instance to cancel one-time or repeating occurrences.
1
this.cancellable = stage().scheduler().scheduleOnce(...);
2
...
3
cancellable.cancel();
Copied!
The Actor receiving the timed event will be notified using the intervalSignal() method of the Scheduled protocol.
1
public interface Scheduled {
2
void intervalSignal(final Scheduled scheduled, final Object data);
3
}
Copied!
It may be implemented something like the following.
1
@Override
2
public void intervalSignal(final Scheduled scheduled, final Object data) {
3
((DataPacket) data).ifAccumulatedEnd(cancellable -> cancellable.cancel());
4
}
Copied!

Implementing Multiple Protocols (Interfaces)

An Actor is not limited to implementing a single protocol or interface. It could have two or more. Consider again the Scheduler example (above). An Actor implementation that wants to schedule timed event signals will be more than a Scheduled type. Its primary purpose is to be another type of Actor, and to its clients that protocol type is the focus. Consider this example.
1
public DocumentProcessorActor extends Actor
2
implements DocumentProcessor, Scheduled {
3
...
4
}
Copied!
Here the primary responsibility of the Actor is to be a DocumentProcessor. The fact that it is capable of being scheduled for timer signals is an internal concern only. The clients of this Actor will not know that it can be a Scheduled, only that it is a DocumentProcessor.
1
// creating a DocumentProcessor
2
final DocumentProcessor = world.actorFor(
3
DocumentProcessor.class, DocumentProcessorActor.class, ...);
Copied!
Still, the responsibility of being an effective DocumentProcessor requires it to schedule itself to receives timer signals. The DocumentProcessorActor may be registered with the Scheduler by passing a reference to itself as a Scheduled. You saw this in the above example, but to make it stand out here is another one that isolates the use of the essential selfAs().
1
// inside an actor
2
final Schedule scheduled = selfAs(Schedule.class);
3
final DataPacket packet = new DataPacket(0);
4
stage().scheduler().scheduleOnce(scheduled, packet, 100, 1_000);
Copied!
All Actor types inherit the method selfAs(Class<T>) to request itself as an Actor that supplies the protocol represented by the generic parameter T. The Actor must implement the T protocol.
Note that you must never pass a reference to yourself using this. Passing this, for example to scheduleOnce(), will cause intervalSignal() notifications to be received as direct method invocations rather than as asynchronous messages. Even though you may think that this could be a good idea, it is definitely a very bad idea. You will eventually experience a race condition in your Actor where a message delivered asynchronously on one thread will collide by accessing data simultaneously with the Scheduler thread that makes the direct method invocations.
You must never pass yourself using this. Always use the Actor inherited methodselfAs(SomeProtocol.class) to comply with the proper use of the Actor Model.
An Actor may implement a number of protocols, such as when representing itself as protocols specifically supported by its children or other collaborators. This makes for loose coupling and least knowledge by design. Even so, care should be used to avoid creating an Actor that supports more protocols than is necessary to meet its primary responsibility.

Returning Actor Message Outcomes

Actors may return values, but must do so by means of Completes<T>, where T is the type of the outcome. If your actor's message protocol that provides a return value answer does not return a Completes<T> value, then the platform runtime will reject the protocol.
The following is a valid protocol for returning a value.
1
public interface TextToInteger {
2
Completes<Integer> convertFrom(final String digits);
3
}
Copied!
Your return value may be provided from inside your actor's message handling method as follows.
1
public class TextToIntegerActor extends Actor implements TextToInteger {
2
@Override
3
public Completes<Integer> convertFrom(final String digits) {
4
return completes().with(Integer.parseInt(digits));
5
}
6
}
Copied!
In some cases an actor is unable to determine a final outcome prior to returning from the message handling method. This is due to the actor depending on another actor requiring asynchronous message sending and an eventual outcome to be answered. Another protocol provides the definition of the Calculator behavior.
1
public interface Calculator {
2
Completes<Integer> calculate(final String digits, final int multiplier);
3
}
Copied!
In such cases the calculate() method may use the Actor base class behavior answerFrom(). This manages the eventual outcome from another actor and and then carries out the final answer.
1
public class CalculatorActor extends Actor implements Calculator {
2
private TextToInteger textToInteger;
3
4
@Override
5
public void start() {
6
textToInteger = childActorFor(TextToInteger.class, Definition.has(TextToIntegerActor.class, Definition.NoParameters));
7
}
8
9
@Override
10
public Completes<Integer> calculate(final String digits, final int multiplier) {
11
return answerFrom(textToInteger.convertFrom(digits).andThen(number -> number * multiplier));
12
}
13
}
Copied!
The CalculatorActor depends on the previous TextToIntegerActor to convert from a String to an Integer before the CalculatorActor can multiply that number by the given multiplier. Due to this asynchronous behavior, the Actor base class behavior answerFrom() is used to manage the asynchronous messaging and outcome, which is then used to calculate the answer, and provide that answer an eventual outcome to the original client.

Actor Supervision

A recent account of cascading failure describes tens of thousands of nodes lost during a Kafka failure that caused a Kubernetes cluster to self destruct, taking out an entire infrastructure. Using supervision as bulkheads can save your system from catastrophic failure.
The following diagram illustrates the contrast between how failure is handled in a reactive, Actor Model architecture, and in a typical blocking architecture. It also provides a good indication of why typical blocking architectures can fail catastrophically, and why reactive architectures tend not to.
How cascading failure is prevented with reactive.
When an actor throws an exception, or when some synchronous dependency in the actor's use throws an exception, and that exception is caught by the XOOM Actors message delivery component, the supervisor of this actor is informed. The supervisor is responsible for what happens to the actor, such as stopping it or resuming its processing, etc.
The default behavior of the system level supervisors is limited in that they decide what to do about the crashed actor based on static policies. An example might be, "if this actor has crashed 10 times in 5 seconds, I'm going to stop it; otherwise I'll just tell it to resume." Obviously creating your own supervisors provides superior customization, but the default system level supervisors protect again catastrophic failure when no specialized supervisors have been provided by the service/application team.
The Actor Model supports scoped supervision of Actor instances. When the World is created with default configuration, the following hierarchy of supervision is established.
1
PrivateRootActor (literal)
2
PublicRootActor (literal)
3
ApplicationActor1 (example)
4
ApplicationActor1_1 (example)
Copied!
A concrete Actor that serves as a supervisor must implement the protocol defined by the io.vlingo.xoom.actors.Supervisor. Two of the standard supervisors know as the PrivateRootActor and the PublicRootActor implement the io.vlingo.xoom.actors.Supervisor protocol. Furthermore, if ApplicationActor1 and ApplicationActor1_1 are to serve as supervisors, they too must implement the io.vlingo.xoom.actors.Supervisor protocol.
The above example demonstrates that there is a base supervisor known as the PrivateRootActor. It is the ultimate supervisor that protects the World from catastrophic failure by serving as an impenetrable shield against lower-level failures. Just below the PrivateRootActor is the PublicRootActor. All top-level application/service Actor instances, such as ApplicationActor1 in the above example, are supervised by the PublicRootActor. Any children of the ApplicationActor1, such as ApplicationActor1_1 in the above example, are supervised by ApplicationActor1.
Thus, any newly created concrete Actor whose parent is known and implements the standard Supervisor protocol is the child's supervisor. If the parent is not known or the new Actor is top-level, then both its parent and its supervisor are assigned as the PublicRootActor.

Supervision Overrides

You may override the default supervisor arrangement using the xoom-actors.properties configuration.
1
plugin.name.override_supervisor = true
2
plugin.override_supervisor.classname =
3
io.vlingo.xoom.actors.plugin.supervision.DefaultSupervisorOverridePlugin
4
plugin.override_supervisor.types =\
5
[stage=default name=overrideSupervisor
6
supervisor=io.vlingo.xoom.actors.plugin.supervision.DefaultSupervisorOverride]
Copied!
This will assign the default supervisor as the plugin DefaultSupervisorOverride, which is explained under the plugins section. This override may also be defined using fluent configuration.
1
final Configuration configuration =
2
Configuration
3
.define()
4
...
5
.with(DefaultSupervisorOverridePluginConfiguration
6
.define()
7
.supervisor("default", "overrideSupervisor",
8
DefaultSupervisorOverride.class))
9
...
Copied!
When an Actor throws an exception, the exception is caught by the runtime. When the exception is caught, the Actor is suspended, meaning that it is not permitted to process any messages until the exception has been handled. The exception will be handled by its supervisor when the exception is reified as a message and sent asynchronously to its supervisor. When received, the exception is interpreted and the supervisor's recovery strategy is employed. The supervisor strategy can specify the following actions.
  • Resume operation of the Actor starting with its next message
  • Restart the Actor
  • Stop the Actor, which implies also stopping any of its children
  • Escalate the recovery up another ancestor level
When the supervisor strategy is to restart, a restart is done only for a maximum number of restarts within a stipulated timeframe. In other words, the Actor may not be permitted to crash repeatedly over an extended period of time. To control restarts or leave them available continuously, the following stipulations may be used.
  • If the current restart intensity count is within the specified intensity over the given period of time, restart the Actor.
  • An example of intensity is 10 times within a period of 5 seconds, or 50 times over a period of 1 minute.
  • You may specify a maximum intensity of an unlimited number of times over an infinite time period.
For examples see the following:
1
io.vlingo.xoom.actors.PublicRootActor
2
io.vlingo.xoom.actors.SupervisionStrategy
3
io.vlingo.xoom.actors.DefaultSupervisor
4
io.vlingo