Rich
Rich

Reputation: 15767

Sending a PoisonPill to an Actor in Java

I am starting to learn Akka by migrating an existing Java SE app to it. I am using Akka 2.0.3.

At one point I need to send a PoisonPill through the message queue to stop the actors. My actor is instantiated thus:

ActorRef myActor = actorSystem.actorOf(new Props(MyActor.class), "myActor");

to which I try to send the PoisonPill:

myActor.tell(PoisonPill.getInstance());

But I get the following compiler error:

'tell(java.lang.Object)' in 'akka.actor.ActorRef' cannot be applied to '(akka.actor.PoisonPill$)'

What am I doing wrong? I'm running Java 1.6.0_26 in Idea (which I am also learning after a lifetime in Eclipse).


Edit:

I have also tried this approach, which is in the documentation, but I get the same compiler error and Idea warns me that the Actors class is deprecated.

import static akka.actor.Actors.*;
extractionActor.tell(poisonPill());

Upvotes: 12

Views: 5910

Answers (3)

snukone
snukone

Reputation: 322

UPDATE FROM 25.03.2019

The good answers from @Viktor Klang and @yash.vyas are a bit out of date. Here is the current working syntax of Scala 2.12.8 and JDK8 (1.8.0_172):

val accountB = context.actorOf(Props[BankAccount], "accountB")
accountB ! PoisonPill

You could also write:

...
accountB ! PoisonPill.getInstance

The default call of the tell-Method is also working:

...
accountB.tell(PoisonPill.getInstance,ActorRef.noSender)

Upvotes: 0

yash.vyas
yash.vyas

Reputation: 163

As mentioned in my reply to the comment above, this does not work in Idea or when using gradle to compile. It is in fact a compilation error since the sender ActorRef is required. I know the previous answers are old, and i'm not sure if this was a change in the api, so for anyone having a similar issue you should be using :

target.tell(PoisonPill.getInstance(), ActorRef.noSender());

For reference see : http://doc.akka.io/docs/akka/snapshot/java/lambda-actors.html#PoisonPill

Upvotes: 6

Viktor Klang
Viktor Klang

Reputation: 26579

Please read the Akka documentation, we've spent a lot of time creating it:

PoisonPill

You can also send an actor the akka.actor.PoisonPill message, which will stop the actor when the message is processed. PoisonPill is enqueued as ordinary messages and will be handled after messages that were already queued in the mailbox.

Use it like this:

   import static akka.actor.Actors.*;
   myActor.tell(poisonPill());

The above approach has been deprecated since 2.0.2, this is the new API:

ActorRef ref = system.actorOf(new Props(JavaAPITestActor.class));
ref.tell(PoisonPill.getInstance());

The above compiles on my machine so you might have some issue in IDEA? Try to compile it with javac and see if that works.

Upvotes: 9

Related Questions