Created
October 4, 2025 03:07
-
-
Save anandwana001/5f6a99ab6f7acda1d4e37920770eeade 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 kotlinx.coroutines.sync.Semaphore | |
| import kotlinx.coroutines.sync.withPermit | |
| import kotlin.system.measureTimeMillis | |
| class RateLimitedApiClient { | |
| private val maxConcurrentRequests = 10 | |
| private val semaphore = Semaphore(maxConcurrentRequests) | |
| suspend fun makeApiCall(id: Int): String = semaphore.withPermit { | |
| withContext(Dispatchers.IO) { | |
| println("API call $id on ${Thread.currentThread().name}") | |
| delay(1000) // Simulate API call | |
| "Response $id" | |
| } | |
| } | |
| suspend fun batchApiCalls(count: Int): List<String> = coroutineScope { | |
| (1..count).map { id -> | |
| async { makeApiCall(id) } | |
| }.awaitAll() | |
| } | |
| } | |
| fun main() = runBlocking { | |
| val client = RateLimitedApiClient() | |
| val time = measureTimeMillis { | |
| val results = client.batchApiCalls(50) | |
| println("Completed ${results.size} API calls") | |
| } | |
| println("Time taken: $time ms") | |
| println("Limited to 10 concurrent requests despite 64 available IO threads") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment