Eventloop module is the foundation of other modules that run their code inside event loops and threads. It provides efficient management of asynchronous operations without multithreading overhead. Particularly useful for building client-server applications with high performance requirements.
You can add Eventloop module to your project by inserting dependency in
represents an infinite loop, where each
loop executes all the tasks that are provided by Selector or stored in
special queues. Each of these tasks should be small and its execution is called
The only blocking operation of Eventloop infinite loop is Selector.select(). This operation selects a set of keys
whose corresponding channels are ready for I/O operations. With these keys and queues with tasks, eventloop asynchronously
executes them in one thread in the overridden method run() (
Eventloop is an implementation of
Eventloop works with different types of tasks that are stored in separate queues:
|Local tasks||Tasks which were added from current Eventloop thread|
|Concurrent tasks||Tasks which were added from other threads|
|Scheduled tasks||Tasks which are scheduled to be executed later|
|Background tasks||Same as Scheduled, but if there are only Background tasks left, Eventloop will be closed|
Execution of an eventloop will be ended when its queues with non-background tasks are empty, Selector has no selected
keys and amount of concurrent operations in other threads equals 0. To prevent Eventloop closing in such cases, you
keepAlive flag (when set true, Eventloop will continue running even without tasks).
In this example we create an eventloop, post a task to it (which is printing out “Hello World” message) and then starting the eventloop:
This example represents how tasks are scheduled in eventloops:
If you run the example, you’ll receive an output which looks something like:
So, the first task to be executed is printing out “Not in eventloop…”, it will be executed even before the eventloop is started. The next executed task is “Thread.sleep(2000)…” as we posted it to the beginning of eventloop’s localTasks. Immediately after that “Eventloop.delay(100)…” and “Eventloop.delay(1000)” are executed as they are already expired. And finally “ventloop.delay(3000)” is executed right at its time.