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());
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());
http://doc.akka.io/docs/akka/2.0.3/java/untyped-actors.html#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.
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
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)
Related
I created a simple scenario.
The following actor systems:
akka.tcp://TestSystem#127.0.0.1:2560
akka.tcp://TestSystem#127.0.0.1:2570
akka.tcp://TestSystem#127.0.0.1:2580
The idea is to create an "SampleActor" from 127.0.0.1:2570 but deploy the actor creation to 127.0.0.1:2560 using the configuration stated on the documentation: Creating Actors Remotely
akka {
actor {
deployment {
/sampleActor {
remote = "akka.tcp://TestSystem#127.0.0.1:2560"
}
}
}
}
And then on 127.0.0.1:2570:
system.actorOf(Props.create(SampleActor.class), "sampleActor");
Now from 127.0.0.1:2580 I wan to find the remote deployed actor and send a message. According to the docs: Looking up Remote Actors
ActorSelection selection =
system.actorSelection("akka.tcp://TestSystem#127.0.0.1:2560/user/sampleActor");
selection.tell("Pretty slick", ActorRef.noSender());
However this does not work. It cannot find the actor on 127.0.0.1:2560. But it works if I change to:
ActorSelection selection =
system.actorSelection("akka.tcp://TestSystem#127.0.0.1:2570/user/sampleActor");
selection.tell("Pretty slick", ActorRef.noSender());
The difference is that on the first one I am looking for the actor where it is deployed, in this case in 127.0.0.1:2560, as the docs say, and on the second case I am looking for the actor where the actor creation was defined, in this case is 127.0.0.1:2570. Why is this happening?, it doesn't make sense, if I am looking for a remote actor then I should look at the place where it was deployed right?
Also when printing the parent at the deployed actor I get:
akka://TestSystem/remote/akka.tcp/TestSystem#127.0.0.1:2570/user
This makes it more confusing as it is not the same as described on the docs: The Interplay with Remote Deployment All of this makes it really confusing, the docs are really long and don't explain properly how to do some basic things properly. Can someone please help me understand this issue?
Well apparently that is just how akka works, it is quite confusing. At the end you should always send messages to the "deployer" not to the deployee. The "deployer" will in turn send the message to the "deployee". Same principle for everything related to remote deployment.
I have a problem while trying my hands on the Hello World example explained here.
Kindly note that I have just modified the HelloEntity.java file to be able to return something other than "Hello, World!". Most certain my changes are taking time and hence I am getting the below Timeout error.
I am currently trying (doing a PoC) on a single node to understand the Lagom framework and do not have liberty to deploy multiple nodes.
I have also tried modifying the default lagom.circuit-breaker in application.conf "call-timeout = 100s" however, this does not seem to have helped.
Following is the exact error message for your reference:
{"name":"akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://hello-impl-application/system/sharding/HelloEntity#1074448247]] after [5000 ms]. Sender[null] sent message of type \"com.lightbend.lagom.javadsl.persistence.CommandEnvelope\".","detail":"akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://hello-impl-application/system/sharding/HelloEntity#1074448247]] after [5000 ms]. Sender[null] sent message of type \"com.lightbend.lagom.javadsl.persistence.CommandEnvelope\".\n\tat akka.pattern.PromiseActorRef$.$anonfun$defaultOnTimeout$1(AskSupport.scala:595)\n\tat akka.pattern.PromiseActorRef$.$anonfun$apply$1(AskSupport.scala:605)\n\tat akka.actor.Scheduler$$anon$4.run(Scheduler.scala:140)\n\tat scala.concurrent.Future$InternalCallbackExecutor$.unbatchedExecute(Future.scala:866)\n\tat scala.concurrent.BatchingExecutor.execute(BatchingExecutor.scala:109)\n\tat scala.concurrent.BatchingExecutor.execute$(BatchingExecutor.scala:103)\n\tat scala.concurrent.Future$InternalCallbackExecutor$.execute(Future.scala:864)\n\tat akka.actor.LightArrayRevolverScheduler$TaskHolder.executeTask(LightArrayRevolverScheduler.scala:328)\n\tat akka.actor.LightArrayRevolverScheduler$$anon$4.executeBucket$1(LightArrayRevolverScheduler.scala:279)\n\tat akka.actor.LightArrayRevolverScheduler$$anon$4.nextTick(LightArrayRevolverScheduler.scala:283)\n\tat akka.actor.LightArrayRevolverScheduler$$anon$4.run(LightArrayRevolverScheduler.scala:235)\n\tat java.lang.Thread.run(Thread.java:748)\n"}
Question: Is there a way to increase the akka Timeout by modifying the application.conf or any of the java source files in the Hello World project? Can you please help me with the exact details.
Thanks in advance for you time and help.
The call timeout is the timeout for circuit breakers, which is configured using lagom.circuit-breaker.default.call-timeout. But that's not what is timing out above, the thing that is timing out above is the request to your HelloEntity, that timeout is configured using lagom.persistence.ask-timeout. The reason why there's a timeout on requests to entities is because in a multi-node environment, your entities are sharded across nodes, so an ask on them may go to another node, which is why a timeout is needed in case that node is not responding.
All that said, I don't think changing the ask-timeout will solve your problem. If you have a single node, then your entities should respond instantly if everything is working ok.
Is that the only error you're seeing in the logs?
Are you seeing this in devmode (ie, using the runAll command), or are you running the Lagom service some other way?
Is your database responding?
Thanks James for the help/pointer.
Adding following lines to resources/application.conf did the trick for me:
lagom.persistence.ask-timeout=30s
hello {
..
..
call-timeout = 30s
call-timeout = ${?CIRCUIT_BREAKER_CALL_TIMEOUT}
..
}
A Call is a Service-to-Service communication. That’s a SeviceClient communicating to a remote server. It uses a circuit breaker. It is a extra-service call.
An ask (in the context of lagom.persistence) is sending a command to a persistent entity. That happens across the nodes insied your Lagom service. It is not using circuit breaking. It is an intra-service call.
I'm currently working with Akka Streams (in Java) for a personal project and I'm having a hard time understanding how to send element to a Source.
The idea is to use a WebSocket to push content into the user's web browser. I've managed to use Akka Streams to create a request-response system, following the Akka HTTP documentation, but this is not what I want to do.
Looking into the Akka Streams documentation, I saw that there is Source.queue and Source.actorRef. But I don't understand how to put an element into the Source. Source.queue and Source.actorRef return a Source, which doesn't have the method offer (for Source.queue) or tell (for Source.actorRef).
My question is: how do I get the ActorRef for the Source created by Source.actorRef or the SourceQueueWithComplete for a Source created with Source.queue, to be able to send elements to my Source?
I searched the various Akka documentation but found no method to do that. And the majority of the code I found on the Internet is written in Scala, which doesn't seem to have the same problem.
The actor and queue from Source.actorRef and Source.queue, respectively, are the materialized values of those sources, meaning that they can be obtained only if the stream is running. For example:
final ActorRef actor =
Source.actorRef(Integer.MAX_VALUE, OverflowStrategy.fail())
.to(Sink.foreach(m -> System.out.println(m)))
.run(materializer);
actor.tell("do something", ActorRef.noSender());
It's no different in Scala:
implicit val materializer = ActorMaterializer()
val actor =
Source.actorRef(Int.MaxValue, OverflowStrategy.fail)
.to(Sink.foreach(println))
.run()
actor ! "do something"
I am using new DefaultConsumer(channel) and overriding handleDeliverymethod.
My goal is to use my consumer as worker queues and for that I know that I have to provide the channel.basicQos(1). Using 1 as my prefetchCount. I have been reading that I also need to provide channel.basicAck in order for my server to know how many unacknowledged messages must be sent(correct me if I am wrong here). Based on this count the channel.basicQos takes effect. Now, I am using the following statements in the handleDelivery method
channel.basicQos(1);
channel.basicAck(envelope.getDeliveryTag(), false);
The issue is, I keep getting the following error:
com.rabbitmq.client.AlreadyClosedException: clean connection shutdown;
reason: Attempt to use closed channel
at com.rabbitmq.client.impl.AMQChannel.ensureIsOpen(AMQChannel.java:190)
at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:223)
.................................
..................................
When I remove the channel.basicAck, I don't see that problem.
How can I use the channel.basicQos to work (My understanding is for this to work, I need to provide the basicAck) and I don't want to get the AlreadyClosedException error.
Thanks for taking the time to read this and for any help you guys can offer!
I have a tricky issue with karaf, and having tried all day to fix it, I need your insights. Here is the problem:
I have camel routes (pure java DSL) that get data from 2 sources, process them, and then send the results to a redis
- when using as standalone application (with a Main class and a command line "java -jar myjar.jar"), data are processed and saved in less than 20minutes
- when using them as a bundle (part of another feature actually) , on the same machine, it takes about 10 hours .
EDIT: I forgot to add: I use camel 2.1.0 and karaf 2.3.2
Now, we are in the process of refactoring our SI to karaf features, so sadly, it's not really possible to just keep the standalone app.
I tried playing with karaf java memory option, using a cluster (I failed :d ) playing with SEDA and threadpool, replacing all direct route by a seda, without success. A dev:create-dump shows a lot of
thread #38 - Split" Id=166 BLOCKED on java.lang.Class#56d1396f owned by "Camel (camelRedisProvisioning)
Could it be an issue with split and parallelProcessing in karaf ? Standalone app shows indeed a LOT more CPU activity.
Here are my camel route
//start with a quartz and a cron tab
from("quartz://provisioning/topOffersStart?cron=" + cronValue.replace(' ', '+')).multicast()
.parallelProcessing().to("direct:prodDAO", "direct:thesaurus");
//get from two sources and process
from("direct:prodDAO").bean(ProductsDAO.class)
.setHeader("_type", constant(TopExport.PRODUCT_TOP))
.setHeader("topOffer", constant("topOffer"))
.to("direct:topOffers");
from("direct:thesaurus")
.to(thesaurusUri).unmarshal(csv).bean(ThesaurusConverter.class, "convert")
.setHeader("_type", constant(TopExport.CATEGORY_TOP))
.setHeader("topOffer", constant("topOffer"))
.to("direct:topOffers");
//processing
from("direct:topOffers").choice()
.when(isCategory)
.to("direct:topOffersThesaurus")
.otherwise()
.when(isProduct)
.to("direct:topOffersProducts")
.otherwise()
.log(LoggingLevel.ERROR, "${header[_type]} is not valid !")
.endChoice()
.endChoice()
.end();
from("direct:topOffersThesaurus")
//here is where I think the problem comes
.split(body()).parallelProcessing().streaming()
.bean(someprocessing)
.to("direct:toRedis");
from("direct:topOffersProducts")
//here is where I think the problem comes
.split(body()).parallelProcessing().streaming()
.bean(someprocessing)
.to("direct:toRedis");
//save into redis
from("direct:toRedis")
.setHeader("CamelRedis.Key", simple("provisioning:${header[_topID]}"))
.setHeader("CamelRedis.Command", constant("SETEX"))
.setHeader("CamelRedis.Timeout", constant("90000"))//25h
.setHeader("CamelRedis.Value", simple("${body}"))
.to("spring-redis://?redisTemplate=#provisioningRedisTemplateStringSerializer");
NB: the body sent to direct:topOffers[products|thesaurus] is a list of pojo (the same class)
Thanks to anyone that can help
EDIT:
I think I narrowed it down to a deadlock on jaxb. Indeed, in my routes, I make lots of call to a java client calling a web service. When using karaf, thread are block there :
java.lang.Thread.State: BLOCKED (on object monitor) at com.sun.xml.bind.v2.runtime.reflect.opt.AccessorInjector.prepare(AccessorInjector.java:78)
further down the stack trace, we see the unmarshalling method used to transform the xml in object, those 2 line we suspect to me
final JAXBContext context = JAXBContext.newInstance(clazz.getPackage().getName());
final Unmarshaller um = context.createUnmarshaller();
I remove the final, no improvements. Maybe something to do with the jaxb used by karaf ? I do not install any jaxb impl with the bundle
Nailed it !
As seen above, it was indeed linked to a deadlock on the jaxb context in my webservice client.
what I did :
- refactoring of the old code for that client by removing the final keyword on Marshaller/Unmarshaller object (I think the deadlock came from there, even if it was the exact same code when runing on standalone)
- instanciate the context based on the package, and only once.
I must admit Classloader issues with OSGI had me banging my head on my desk for a few hours, but thanks to Why can't JAXB find my jaxb.index when running inside Apache Felix? , I manage to fix that
Granted, my threads are now sleeping instead of blocked, but now I process my data in less than 30 min, so that's good enough for me