Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start Akka Actors since 2.0?

Tags:

scala

akka

actor

I'm using Akka Actors and I'm trying to update my code to use the latest 2.0 milestone. The API changed somewhat, for example the creation of Actors now works via something called an ActorSystem.

Starting and stopping actors changed as well - the latter is available via the ActorSystems methods .stop(..) and .shutdown(). But I can for the life of me not figure out how to start them... The documentation is good, but seems to be missing some important points. I feel kinda stupid to ask, but how do you start actors in your Akka 2.0 environment? If I understood correctly actors who have a 'parent' are started when this parent is started - but what about the top level actor(s)?

like image 985
fgysin Avatar asked Dec 29 '11 09:12

fgysin


1 Answers

In Akka 2.0, there is no need for a start() method because Actors are started as soon as you instantiate them in the context of an ActorSystem (or another Actor) -- but you need to instantiate them with one of the provided methods of ActorSystem or an Actor's context.

So, for example, if you have an Actor subclass called MyClass, you could start it with:

val system = ActorSystem()
val myActor = system.actorOf(Props[MyActor])

or, if your actor took constructor arguments:

val myActor = system.actorOf(Props(new MyActor("arg1"))

or, if you were in the body of another Actor,

val myActor = context.actorOf(Props(new Actor("arg1"))

and then your actor could immediately receive messages, e.g.

myActor ! MyMessage

Even your top level actors are started immediately, as all Actors in 2.0 are automatically in a supervision hierarchy. As soon as the actor is instantiated with the ActorSystem, it's ready to receive messages.

like image 183
Josh Marcus Avatar answered Sep 29 '22 04:09

Josh Marcus