I have looked around and found this explaining how to execute code in parallel, however my code is running in a Spring Boot app, not on Android, so I believe the dispatchers should be different.
At any rate, the following code does not run in parallel (only runs on a single thread -- http-nio-8080-exec-1 -- in sequence). So, it's taking over 4 seconds when it should take a little more than 2 seconds:
import kotlinx.coroutines.*
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate
@RestController
class CoroutineController {
@GetMapping("/")
suspend fun find(): String {
var result = ""
coroutineScope {
val start = System.currentTimeMillis()
println(Thread.currentThread().name + " starting at " + start)
val product = async {
findById()
}
val product2 = async {
findById2()
}
result = product.await() + product2.await()
println(Thread.currentThread().name + " ending " + (System.currentTimeMillis() - start))
}
return result
}
suspend fun findById(): String {
println(Thread.currentThread().name + " starting find 1")
val restTemplate = RestTemplate()
val response = restTemplate.getForObject("https://httpbin.org/ip", String::class.java)
Thread.sleep(2000)
return response!!
}
suspend fun findById2(): String {
println(Thread.currentThread().name + " starting find 2")
val restTemplate = RestTemplate()
val response = restTemplate.getForObject("https://httpbin.org/ip", String::class.java)
Thread.sleep(2000)
return response!!
}
}
Output in console:
http-nio-8080-exec-1 starting at 1607845427335
http-nio-8080-exec-1 starting find 1
http-nio-8080-exec-1 starting find 2
http-nio-8080-exec-1 ending 4783
How to best make the calls findById and findById2 to run in parallel (i.e. on separate threads) so as to save loading time?