I have a function that divide and conquers a CPU-i...
# coroutines
m
I have a function that divide and conquers a CPU-intensive task using coroutines. I want to test that it actually runs concurrently in a unit test. If I were using threads, I would have called the function tasks that awaited a common
CyclicBarrier
. How can I achieve something similar with coroutines?
My current workaround is:
Copy code
coroutineCounter -= 1  // a @Volatile field
yield()
assert(coroutineCounter == 0)
Seems to work, but I'm not sure if it's guaranteed to work.
e
When you say “concurrently” what do you mean? Do you “concurrently” (as in — different pieces of code run in different coroutines) or do you mean “in parallel” (different pieces of code run in different threads)?
m
I started writing the test when fixing code that someone in my team wrote. He used
runBlocking
and
async
, but didn't realize that you have to use a suspending function. The result was that he thought things run in parallel, even though it wasn't.
So I guess in this case, things were neither concurrent or parallel (i.e. no coroutines and all in the same thread).
Ideally, I'd like to test that things are running in parallel, but I think that might be hard, so testing that it's running concurrently would be good enough.
Love your work btw @elizarov. It's a pleasure to work with Kotlin in the backend 🙂
e
You can test for parallel just like in Java. Create your own executor with N thread, run a test that is supposed to do N pieces of work in parallel, then use CyclicBarrier with N parties to ensure they all indeed in different threads.
m
Thanks! You're right, I made a mistake 😐