I am using akka scheduler as shown in below code.
Each user can login to my Application and can create scheduler for background task.I am using Akka scheduler for this purpose.
For each user Id I am calling buildScheduler method as shown below. Before calling this method I am cancelling the existing scheduler using Cancellable object for the same user Id. (I implemeted static map with user ID as key and Cancellable object as value)
Even after I cancel existing scheduler,actorSystem.actorOf() gives error actor name not unique error.
I would like to understand what exactly happen when we cancel the scheduler using Cancellable instance ? Does it kill the ActorRef as well, if not should we reuse the same ActorRef every time we call this buildScheduler method ?
What about message, will it be in memory forever even after we call cancel on Cancellable instace and memory will get clean up only when garbage collector invoke ?
public Cancellable buildScheduler(String actorName, SchedulerActorMessage message, long interval, TimeUnit timeUnit, long initialDelay, String actorMapKey) {
ActorRef daemonRef = actorSystem.actorOf(Props.create(SchedulerActor.class), actorName);
Cancellable cancellableActor = actorSystem.scheduler().schedule(FiniteDuration.apply(initialDelay, timeUnit),
FiniteDuration.apply(interval, timeUnit), daemonRef, message,
actorSystem.dispatcher(), ActorRef.noSender());
actorMap.put(actorMapKey, cancellableActor);
return cancellableActor;
}
I am new to actor and have very basic knowledge, please pardon me if this question does make much sense.
I would like to understand what exactly happen when we cancel the scheduler using Cancellable instance ? Does it kill the ActorRef as well
No, it doesn't. The actor's lifecycle is independent of the scheduled task.
should we reuse the same ActorRef every time we call this buildScheduler method
This depends on your use case, if your actor maintains state that you want to keep between schedules, you should create the actor outside of buildScheduler
and pass the ActorRef
.
What about message, will it be in memory forever even after we call cancel on Cancellable instace and memory will get clean up only when garbage collector invoke
In Java, memory is always reclaimed by garbage collector, so after the task is cancelled and if the passed SchedulerActorMessage
is no referenced by, for example, the buildScheduler
caller, it will be garbage collected.