Criwran
Criwran

Reputation: 431

how to implement coroutine pool in coroutine-support language?

I'm wondering if it is approriate to implement coroutine pool in kotlin since coroutine itself is more lightweight than thread.

There's such a scene, code was wittern in Java: I designed different kind of messages which are received from clients. These messages will be extracted a msgId and encapsulated into a task(which actually a Runnable in Java), and finally be dispathced to different consumption queues according to msgId.

The consumption queues actually are thread pool. These tasks will finally be processed by the processor related to the pool.

/*    
    The whole process is simplified into the following process method
*/
class MsgProcess {
    public void process(Msg msg) {
        int msgId = msg.getId();
        Task task = new AbstractTask(msg);
        Processor processor = ProcessorMap.getProcessorById(msgId);
        QueueDriver driver = processor.getDriver();
        driver.addTask(task);
    }
}

abstract class Processor {
    ...

    protected abstract QueueDriver getDriver(); // QueueDriver is the consumption queue
}

abstract class AbstractTask implements Runnable {
    ...

    @Override
    public void run() {
        ...
    }
}


class Task1 extends AbstractTask{
    @Override
    public void run() {
        // remote procedure call to the script server to process the task
    }
}

Then an idea came into my mind, if in languages like Go and Kotlin that support coroutine, What can thread pools be replaced? To design a coutine pool? Coroutine has already been lightweight. Is pooling design really meaningful

Or how to involve consumption queues for different tasks using coroutine?

Upvotes: 0

Views: 272

Answers (1)

Tenfour04
Tenfour04

Reputation: 93629

When Kotlin documentation talks about coroutines being lightweight threads, it’s just because coroutines use thread pools under the hood. Therefore, pooling coroutines would not provide any benefits, while it would defeat the other primary purpose of coroutines, simpler concurrency-related code.

Upvotes: 1

Related Questions