Dispatch commands to multiple coroutines without blocking input

I want to read input commands from multiple blocking sources and dispatch them to multiple other coroutines based on the command name.

For example, suppose I have a map: val handlers: Map<String, CoroutineScope>

As I haven’t found any methods of reading System.in without blocking the thread, I have to start a thread dedicated for reading stdin.
There may also be other threads e.g. reading from a websocket that accepts commands at indefinite time.

Each command is parsed to a String cmd, and the command should be handled in a new coroutine that runs in handlers[cmd].

The coroutine scopes in the handlers map may or may not run in the same Java thread.

Since multiple commands may be dispatched from the same input within short periods of time, but each command may take a long time (whether suspended for a long time or actually blocking the thread of the handler’s coroutine scope) to complete, it is not appropriate to block the same input reader while the command is being executed.

How should I organize my coroutines, and how should I invoke them from the input sources?

1.3 introduces a dispatcher especially for blocking io called Dispatchers.IO. You can use it to handle your reading. Also it is possible to handle read operations on regular threads and send all the information into Channel.

Isn’t Channel experimental?

It is, but you asked how to do it better. Couroutines without channels are a bit handicapped.

1 Like

I see. The experimental coroutines in 1.2 were a nightmare for me as the lots of deprecation and outdated results on Google Search made it almost impossible to find the right results, so I’m a bit reluctant to try experimental features on something I’m not familiar with.

You can consider Reactor library

1 Like