mkojadinovic
09/24/2021, 12:36 PMprivate suspend fun getSomething() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
RestTemplate().exchange(
"url", <http://HttpMethod.POST|HttpMethod.POST>, HttpEntity("body"), String::class.java
)
}
Will this produce many threads to wait, or I am safe that this will use some limited thread pool? What if I want to limit thread pool size to 2, will it also work?Joffrey
09/24/2021, 12:42 PM<http://Dispatchers.IO|Dispatchers.IO>
which is meant for this, so it's generally OK to do. The IO
dispatcher uses a thread pool that grows as needed to handle all the simultaneous blocking operations. It will block threads, but not the thread of the caller of getSomething()
, that's why it's useful. The IO pool will not grow indefinitely though, only up to 64 threads IIRC.
If you want to limit this to less threads, you can also create your own thread pool and provide it as dispatcher instead of <http://Dispatchers.IO|Dispatchers.IO>
. For that you can use newFixedThreadPoolContext but don't forget to close it in whatever lifecycle hook Spring provides for your component.Joffrey
09/24/2021, 12:48 PMmkojadinovic
09/24/2021, 12:49 PMmkojadinovic
09/24/2021, 12:54 PMJoffrey
09/24/2021, 1:18 PMJoffrey
09/24/2021, 1:24 PMspring.mvc.async.request-timeout
property - I know it says MVC but it works for webflux)mkojadinovic
09/24/2021, 1:36 PMJoffrey
09/24/2021, 1:59 PMif I am not sure if some code is blocking I can just use withContext(Dispatchers.IO) and stop worrying about itIn general you can use
<http://Dispatchers.IO|Dispatchers.IO>
for blocking code and not worry too much about it, although of course if you can find a non-blocking way it will save some resources.
Can I be sure that if I use withContext(Dispatchers.IO) with some blocking code that all of my users will be served eventually?Using
<http://Dispatchers.IO|Dispatchers.IO>
will not drop tasks if the thread pool reached max capacity and all threads are busy. When this happens, the callers of withContext(IO)
will just be suspended longer, but eventually this will run. Of course, unless the server runs out of memory before it has a chance to run them, nothing is magical here ๐mkojadinovic
09/24/2021, 2:15 PMJoffrey
09/24/2021, 2:35 PMmkojadinovic
09/24/2021, 3:15 PMmkojadinovic
09/24/2021, 3:16 PMuli
09/24/2021, 5:34 PM