Created
July 13, 2020 16:51
-
-
Save pkulak/ff269fb6f402ce6f9117c6813dfe2e94 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
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