I'm using Kotlin in my API backend. I don't want to run db queries in the common pool
. Basically, I want to create a CoroutineContext
that has a number of threads that matches the database maximumPoolSize
.
What's the best way to accomplish this (generally and for my specific use case)? I know Kotlin provides contexts
out of the box, but what's the best approach to create my own?
Bonus question: If I have a jdbc connection pool size of 3, does it make sense to use a coroutinecontext with a thread pool size of 3? Can this guarantee the best concurrency possible?
You can create a CoroutineContext
that's backed by a thread pool with a fixed number of threads using newFixedThreadPoolContext
:
val myContext = newFixedThreadPoolContext(nThreads = 3, name = "My JDBC context")
And yes, it seems like a good idea to match your thread pool's size to the connection pool's size, because that way your threads (assuming they each use one connection at a time) will always have a database connection ready for them - here's a blog post suggesting the same.