Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 19, 2024
In this tutorial, we’re going to understand the warning “inappropriate blocking method call”.
We’ll learn why the IDE gives us that warning by first writing an inappropriate call and then what steps we can take to make an appropriate call.
An inappropriate blocking method call is a call to a function that blocks the current Thread while inside a CoroutineContext. Coroutines allow us to create asynchronous programs fluently. Mixing their asynchronicity with a Thread that blocks removes the benefits that coroutines have to offer.
Let’s start by using Thread.sleep() to create a blocking call inside a suspend function:
suspend fun sleepThread() {
Thread.sleep(100L)
}
We’ll get the warning from our IDE as expected:
Possibly blocking call in non-blocking context could lead to thread starvation
To turn an inappropriate call into an appropriate one, we must bring the non-coroutine blocking call to the coroutine world. When we’re in suspendable functions, we can use withContext to tell the coroutine engine which Dispatcher we want it to use. The only way to escape this situation is to wrap the blocking code in the IO Dispatcher:
suspend fun sleepThread() {
withContext(Dispatchers.IO) {
Thread.sleep(100L)
}
}