How to put actor to sleep?
Asked Answered
G

2

1

I have one actor which is executing a forever loop that is waiting for the availability of data to operate on. The doc says the Actor runs on a very lightweight thread, so I'm not sure whether i can use the thread.sleep() method on that actor. My objective is to not have that actor consume too much processing power.

So can I use the thread.sleep() method inside the actor ?

Gunner answered 19/8, 2015 at 9:14 Comment(1)
aah got it. Better to keep on passing command to that actor.Gunner
H
3

Don't sleep() inside Actors! That would cause the Thread to be blocked, causing exactly what you're trying to avoid - using up resources.

Instead if you just handle the message and "do nothing", the Actor will not use up any scheduling resources and will be just another plain object on the heap (occupying around a bit of memory but nothing else).

Hewlett answered 19/8, 2015 at 12:57 Comment(2)
I'd like to add that to keep on handling that message and do nothing, i have to use UntypedActor so i could use the self method. Before this i use TypedActor.Gunner
If by "keep on handling that message" you mean keep working on it, you can start a Future that encapsulates that work, and put it on a different dispatcher, so that it does not use up the actor's dispatcher resources. TypedActors are discouraged in any case as they're 10x slower than untyped ones (related, we are working on akka-typed which solves this doc.akka.io/docs/akka/snapshot/scala/typed.html )Plat
P
0

I just schedule to send a "WakeUp" message in a future time. Akka will send that message at predefined time, so the actor can handle and continue processing. This is to avoid using sleep.

        // schedule to wake up
        getContext().getSystem().scheduler().scheduleOnce(
            FiniteDuration.create(sleepTime.toMillis(), TimeUnit.MILLISECONDS),
            new Runnable() {
              @Override
              public void run() {
                getContext().getSelf().tell(new WakeUpMessage());
              }
            },
            getContext().getSystem().executionContext());
Put answered 6/6, 2022 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.