Kotlin Coroutines and Race Detection


#1

I really like being able to write multi-threaded code using Kotlin Coroutines with channels and fibers in a similar way as in Go. Now Go has some good tool to detect race conditions and deadlocks at runtime that can be switched on with a flag to the runtime or compiler. This tool is written in C++ and was developed at Google for various purposes, not only for Go. Whatever, the point is that with running that race detector when testing your Go application you can get the number of races very very low.

Question is now what can be done to have that kind of runtime analysis for Kotlin Coroutines. There are already tools like this one for Java: vmlens besides other (that are much more expensive). Would that kind of tools written for Java also work with Kotlin Coroutines (since the Koltin compiler carries some meta data around for Coroutines)? Anyway, are there some plans/ideas how race/deadlock detection could be done for Kotlin Coroutines?


#2

Go relies on LLVM race-detector. Similarly, with Kotlin you can use any JVM-based race-detectors. I personally highly recommend DRD: https://code.devexperts.com/display/DRD/About+Data+Race+Detector Unfortunately, most of its documentation is in Russian, but it is the best such JVM-based tool out there (the fastest one). In some future, with Kotlin Native, you’ll be able to use LLVM race-detector, too.

The similar, but more complicated, story is with deadlocks. The detection of deadlocks that did happen is built into JVM. To detect potential deadlocks, I’d recommend dlcheck: https://github.com/Devexperts/dlcheck While built-in JVM detector will not see Mutex-based deadlocks, it should be possible to make dlcheck coroutine-aware and support Mutex, too.

The deadlocks you can get into with channels are more nuanced. Go deadlock detector does a really bad job on detecting them. It really works only on a slide-ware kind of code. It is of no use in complex applications. It is easy to replicate its functionality in Kotlin, but I’m not sure it is worth it. Anyway, Rob Pike asserts that you rarely get into communication deadlocks in practice, so, again, It does not seem that there is a lot of motivation to work in that direction.


#3

The chapters “7 - Deadlock: An introduction” and “8 - Client-Server: Deadlock Avoidance by Design” from Jon Kerridge’s book “Using Concurrency and Parallelism Effectively - Tome 1” are very enlightening for a mere mortal like me… :slight_smile:

And again, Bravo for all the work in Kotlin-Coroutines.