Skip to content

Instantly share code, notes, and snippets.

@pkulak
Created July 13, 2020 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkulak/ff269fb6f402ce6f9117c6813dfe2e94 to your computer and use it in GitHub Desktop.
Save pkulak/ff269fb6f402ce6f9117c6813dfe2e94 to your computer and use it in GitHub Desktop.
fun main() {
val nonBlockingTime = measureTime { runBlocking { nonBlocking() } }
println(nonBlockingTime)
val pool = Executors.newFixedThreadPool(1000)
val blockingTime = measureTime { blocking(pool) }
println(blockingTime)
}
suspend fun nonBlocking(total: Int = 1000) = coroutineScope {
val jobs = mutableListOf<Job>()
val client = HttpClient()
for (i in 0 until total) {
val job = async {
val resp = client.get<String>("https://s3-us-west-2.amazonaws.com/public.kulak.us/threading.html")
}
jobs.add(job)
}
jobs.forEach { it.join() }
}
fun blocking(pool: ExecutorService, total: Int = 1000) {
val latch = CountDownLatch(total)
val connections = PoolingHttpClientConnectionManager().apply {
defaultMaxPerRoute = total
maxTotal = total
}
val client = HttpClients.custom()
.setConnectionManager(connections)
.build()
for (i in 0 until total) {
pool.submit {
val get = HttpGet("https://s3-us-west-2.amazonaws.com/public.kulak.us/threading.html")
val resp = client.execute(get)
resp.entity.writeTo(OutputStream.nullOutputStream())
resp.close()
latch.countDown()
}
}
latch.await()
client.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment