Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Suspend function blocks main thread

I'm having a hard time understanding coroutines. This is a very simple setup. Both longComputation and delay are suspend functions. The first one blocks the main thread, the latter doesn't. Why?

CoroutineScope(Dispatchers.Main).launch {
    val result = longComputation() // Blocks
    delay(10_000) // Doesn't block
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

That depends. What does longComputation do exactly? When you mark a function as suspend, this does not mean you can't include blocking code in it. For instance, have a look at this one:

suspend fun blockingSuspendFunction(){
    BigInteger(1500, Random()).nextProbablePrime()
}

The code inside the suspend function is obviously something that utilizes the CPU and blocks the caller. By convention, this should not be done because if you call a suspend function, you expect it to not block the thread:

Convention: suspending functions do not block the caller thread. (https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761)

To make such a function "behave as a suspending function", the blocking has to be dispatched onto another worker thread, which (by recommendation) should happen with withContext:

suspend fun blockingSuspendFunction() = withContext(Dispatchers.Default) {
    BigInteger.probablePrime(2048, Random())
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!