Hey... I'm writing some http endpoints that I want...
# server
m
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
Coroutines should be better option than implementing our own threads.
m
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
You probably want to launch a coroutine in a managed context / dispatcher, e.g.
Copy code
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
keep in mind you will need graceful shutdown
1
j
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
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
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
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
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.