Skip to content

Latest commit

 

History

History

kotlin

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

Kotlin sample looking concurrency in fetchAndSum()

Compile with gradlew build and run gradlew run

Comparing the use of foreach loop without lambdas and the use of a pipeline (such as ....asSequence().map(...).reduce(...)) with lambdas and the resulting sequential versus concurrent behavior.

suspend fun fetchAndSum(vararg urls: String): Int {
  var sum = 0
  for (url in urls) {
    println("FETCHING from $url")
    val resp = httpClient
        .sendAsync(request(url), BodyHandlers.ofString())
        .await()
    println("=======> from $url")
    sum = sum + resp.body().length
  }
  return sum
}
suspend fun CoroutineScope.fetchAndSumλ(vararg urls: String): Int {
  return urls
    .asSequence()
    .map { url -> async {
      println("FETCHING from $url")
      val resp = httpClient
            .sendAsync(request(url), BodyHandlers.ofString())
            .await()
      println("=======> from $url")
      resp.body().length
    }}
    .reduce { prev, curr -> async {
      prev.await() + curr.await()
    }}
    .await();
}
FETCHING from https://stackoverflow.com/
=======> from https://stackoverflow.com/
FETCHING from https://github.com/
=======> from https://github.com/
FETCHING from http://dzone.com/
=======> from http://dzone.com/
Total chars = 470831
FETCHING from https://stackoverflow.com/
FETCHING from https://github.com/
FETCHING from http://dzone.com/
=======> from https://github.com/
=======> from https://stackoverflow.com/
=======> from http://dzone.com/
Total chars = 470831