Search code examples
kotlinasynchronouskotlin-coroutinesblockingnonblocking

Suspend keyword as redundant with Network Request function in Spring Boot Application


I've been delving into Kotlin Coroutines and discovered that suspending functions can simplify the creation of asynchronous and non-blocking code when using Kotlin and Coroutines. In an Android application, making Network Requests as suspending functions is crucial to prevent blocking the Main Thread.

However, in a Spring Boot Application, where the concept of a Main thread isn't as prominent, there are situations where we need to wait for the Network call to return before proceeding with the next steps, which might seem somewhat 'blocking'. I even attempted to apply the suspend keyword to my client calls and launch them within Coroutines. Interestingly, Kotlin sometimes suggests that the 'suspend' keyword is redundant.

This raises the question of whether Network Requests or other I/O-bound operations can truly be considered or implemented as suspend methods in a Spring Boot context. If there is a way to implement them as suspending functions, what advantages would this bring to REST calls?

// suspend here is redundant...in fact, if this call takes x seconds, my API request thread will be blocked for x seconds
suspend fun makeHttpRequest(): String {
    val client = HttpClient()
    val response = client.get<String>("https://example.com/api/endpoint")
    return response
}

fun main() {
    val numberOfThreads = 4 // Adjust as needed
    val threadPool = newFixedThreadPoolContext(numberOfThreads, "CustomThreadPool")

    runBlocking {
        repeat(numberOfThreads) {
            GlobalScope.launch(Dispatchers.Default + threadPool) {
                val result = makeHttpRequest()
                // Process the result here
            }
        }
    }
}

Solution

  • Async/non-blocking network stack works with coroutines if and only if you use Spring Webflux.

    Spring provides non-blocking compatibility with coroutines through Reactor (reactive streams) and Netty.

    You can get more information in the following blog post section: Webflux with coroutines API.