Advantages and Problems with Mutex

Learn about the important advantage of mutex over the synchronized block as well as the problems with mutex.

Advantage

The vital advantage of mutex over a synchronized block is that we suspend a coroutine instead of blocking a thread; this is a safer and lighter approach. Compared to using a dispatcher with parallelism limited to a single thread, a mutex is lighter, and in some cases, it might offer better performance.

Problems

On the other hand, it’s also harder to use it properly.

Deadlock

It has one crucial danger: a coroutine cannot get past the lock twice (maybe the key stays in the door, so another door requiring the same key would be impossible to get past). Executing the code below will result in a program state called deadlock—it will be blocked forever.

Get hands-on with 1200+ tech skills courses.