Kotlin Coroutines and Loom

Loyal viewer David had a lot of questions in the comments to the last episode (https://youtu.be/ACk2HkvVKnA), where we learned to compose higher order functions to create http4k request handlers. He liked the idea, but was worried about the performance of calling business logic that used Kotlin coroutines from the non-suspend handlers.

This got me wondering whether project Loom and Java virtual threads make this a non-issue. So today I’ll start by looking at why operating system threads limit the throughput of our servers, and how virtual threads solve that problem. Once we have that working, then we can use more virtual threads to invoke suspend functions from plain-old functions like http4k handlers.

With project Loom I think we really can have the best of both worlds, and that I have the benchmarks to prove it.

In this episode

  • 00:00:55 Create an http4k server and make actual HTTP requests to it
  • 00:05:14 Now use an executor to make the requests
  • 00:07:42 Now submit 1000 simultaneousish requests
  • 00:08:25 Measure just the time to process the requests
  • 00:10:42 Shift the checking of the Responses out of the executor code
  • 00:12:43 Separate setup from the measurement
  • 00:15:00 Calling a slower function is much slower because we exhaust the server thread pool
  • 00:16:42 We can use Loom virtual threads to “not have” a thread pool
  • 00:19:30 The results are in
  • 00:20:15 Some connection reset errors?
  • 00:21:25 Rationalised code to record performance and errors
  • 00:23:08 More throughput results
  • 00:23:45 More on those connection resets
  • 00:27:36 Now what about calling suspend funs?
  • 00:32:59 Review

There is a playlist of http4k content https://www.youtube.com/playlist?list=PL1ssMPpyqocg5TKqmiGWlvi3O5L8XPe8Q

If you like this, you’ll probably like my book Java to Kotlin, A Refactoring Guidebook (http://java-to-kotlin.dev). It’s about far more than just the syntax differences between the languages – it shows how to upgrade your thinking to a more functional style.

submitted by /u/dmcg
[link] [comments]