puniverse / quasar

Fibers, Channels and Actors for the JVM
http://docs.paralleluniverse.co/quasar/
Other
4.56k stars 575 forks source link

Usage Question: Scheduling tasks within a fiber without spawning a new thread #312

Open sheldonkreger opened 6 years ago

sheldonkreger commented 6 years ago

I'm looking for a way to periodically execute a function inside a ServerActor. This should continue indefinitely until the ServerActor is terminated. In Java, this is typically done by creating a new thread and running a timer. Even in the Quasar tests for Actor, sleep() is used to cause a delay between function calls, which of course creates a new thread.

https://github.com/puniverse/quasar/blob/master/quasar-actors/src/test/java/co/paralleluniverse/actors/ActorTest.java#L185

Coming from the Erlang/Elixir world, I have been happy with an implementation like this, where the GenServer passes itself a message periodically.

https://stackoverflow.com/a/32097971/1289597

My concern is that if I instantiate ServerActors using spawn() rather than spawnThread(), each instance will run in a fiber. However, if I put a sleep() inside one of the methods to handle scheduling, I now have both a fiber and a thread associated with this ServerActor. This seems risky in regard to scaling.

Is there a standard way to implement lightweight task scheduling using fibers in Quasar?

doctorpangloss commented 6 years ago

Even in the Quasar tests for Actor, sleep() is used to cause a delay between function calls, which of course creates a new thread.

In that code, it's used to just prevent the actor from dequeueing both message uninterrupted.

I now have both a fiber and a thread associated with this ServerActor

Sort of.

When you call Strand.sleep in a fiber, you'll eventually schedule the fiber to be unparked by this:

https://github.com/puniverse/quasar/blob/1a463dac05482e9425777b9510296d6d6af010d0/quasar-core/src/jdk8/java/co/paralleluniverse/fibers/FiberForkJoinScheduler.java#L148

That's it!

The state of the timer ultimately is stored in your fiber scheduler instance. You can also create a "timer actor" that sends messages at the right period.