https://kotlinlang.org logo
Title
m

Michael Ralston

09/17/2021, 10:38 AM
Hey... I'm writing some http endpoints that I want to return immediately and then do their work in the background. Can I use cooroutines for this or would threads be better?
b

Baidyanath

09/17/2021, 10:43 AM
Coroutines should be better option than implementing our own threads.
m

Michael Ralston

09/17/2021, 10:47 AM
how do i write a coroutine that continues executing after the function that called it as finished? my understanding of the documentation is that you have to wrap them in a
runBlocking
statement?
e

evestera

09/17/2021, 12:36 PM
You probably want to launch a coroutine in a managed context / dispatcher, e.g.
launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread
    println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}")
}
https://kotlinlang.org/docs/coroutine-context-and-dispatchers.html#dispatchers-and-threads Though you could very well just use an
ExecutorService
if you don't really need any of the coroutine features.
e

enleur

09/17/2021, 1:44 PM
keep in mind you will need graceful shutdown
1
j

Joffrey

09/17/2021, 3:25 PM
In general, the component handling the requests has some sort of lifecycle. You can create a
CoroutineScope
in that component and
cancel()
it when that lifecycle ends (to avoid leaking coroutines). Use this scope to launch the coroutines that must outlive the function that starts them
l

Luiz Aguiar

09/18/2021, 10:01 PM
Maybe a kind of "queue/scheduler" that consumes whatever you have added from the endpoint execution. Depending on the framework that you are using, you can have some sorts of events that might also works for your scenario.
m

Michael Ralston

09/19/2021, 9:06 PM
Yeah I still feel like a ThreadPoolExecutor is a better solution for what I need. Can queue tasks and bound how many run at once etc.
j

Joffrey

09/19/2021, 9:30 PM
You can use the thread pool as a dispatcher for coroutines, the difference is in the API but you can do the same thing
j

James Richardson

09/23/2021, 7:04 AM
Neither are a good solution, if your processing needs to be reliable. The server process can die at any time, and then both coroutines and threads would be gone. Often, this kind of behaviour is implemented by the http server putting a message on a queue, then a queue worker dealing with the actual work.