Created
October 4, 2025 03:08
-
-
Save anandwana001/43e11a169147e5a3ad0aa2ef2bdb3802 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import kotlinx.coroutines.* | |
| import java.util.concurrent.Executors | |
| class DatabaseService { | |
| // Custom dispatcher with limited threads matching DB connection pool | |
| private val dbDispatcher = Executors.newFixedThreadPool(5).asCoroutineDispatcher() | |
| data class QueryResult(val data: List<String>) | |
| suspend fun executeQuery(query: String): QueryResult = withContext(dbDispatcher) { | |
| println("Executing '$query' on ${Thread.currentThread().name}") | |
| delay(200) // Simulate query execution | |
| QueryResult(listOf("result1", "result2")) | |
| } | |
| suspend fun executeBatchQueries(queries: List<String>): List<QueryResult> = coroutineScope { | |
| queries.map { query -> | |
| async { executeQuery(query) } | |
| }.awaitAll() | |
| } | |
| fun shutdown() { | |
| dbDispatcher.close() | |
| } | |
| } | |
| fun main() = runBlocking { | |
| val dbService = DatabaseService() | |
| try { | |
| val queries = List(20) { "SELECT * FROM table WHERE id = $it" } | |
| val time = measureTimeMillis { | |
| val results = dbService.executeBatchQueries(queries) | |
| println("Executed ${results.size} queries") | |
| } | |
| println("Time: $time ms (limited by 5 DB connections)") | |
| } finally { | |
| dbService.shutdown() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment