Suspend functions and blocking JDBC

Hi, I’m new to Kotlin. I’d like to know: since I’m calling JDBC blocking operations from within a Ktor HTTP handler function, which is suspended, do I need to do something special that I’m not aware of? Searching around, I’ve read a few things about Dispatchers.IO. Would this be the most optimal way to handle blocking operations within a non-blocking context?

Please consider to use a dedicated Dispatcher: Dispatchers.IO.limitedParallelism(nThreads)

nThreads should be equal to JDBC parallelism level, guaranteed by a Semaphore and by configuration of JDBC connection pool.

Sample code:

private const val JDBC_PARALLELISM = 5
private val jdbcDispatcher = Dispatchers.IO.limitedParallelism(JDBC_PARALLELISM)
private val jdbcSemaphore = Semaphore(JDBC_PARALLELISM)

suspend fun <T> useConnection(block: suspend (Connection) -> T): T =
    jdbcSemaphore.withPermit {
        jdbcDispatcher.invoke {
            val connection: Connection = TODO()
            connection.use { block (it)}
        }
    }

See: limitedParallelism

2 Likes

Do we benefit from using a semaphore and limited parallelism at the same time? Assuming block is not suspendable, I would assume using a semaphore or limiting the parallelism should result in a similar behavior.

1 Like

Thanks, i’ll try this out.

You are right, I fixed my miss.