Asynchronous execution in Kotlin and Swift: Concurrency problems and how to solve them

In the previous story, we reviewed a basic sample of asynchronous execution. You probably already know the two common problems with concurrency, shared mutable state and dead-locks. These problems are common in both languages and they have similar resolutions. Let’s take a look at them.

We will start with Shared Mutable State. In an example below, we try to increment some int value 1000 times asynchronously.

As expected, the value is not equal to 1000 and varies from time to time. The solution of Shared Mutable State is pretty simple: we need to synchronize mutable variable reading and writing. It means, that reading and writing operations should be executing on the same thread serially.

You may notice that here we just convert our asynchronous code into synchronous and we don’t gain any benefits of multithreading execution. Yes, it’s true because here we don’t do anything but just changing mutable state. In the real code, there could be a large part with a calculation that needs to be executed in the background and only saves a result of its execution serially.

The second problem is called Dead-Locks. In general, it happens when some code block is waiting till the second block finishes its execution but it also waits for the first block to finish.

In these samples, we use a single-thread queue and two blocks of code. In the first block, we start the second synchronously, so it pauses its execution until the new block finished its execution. But the second block won’t start because it’s pushed to the end of the working queue and cannot start unless the previous block is finished. My advice to avoid such kind of deadlocks: do not use the same queue for nested asynchronous blocks.

That was most common concurrency problems, which I faced by myself. As you see, concurrency problems and their solutions look very similar in both languages. That was one of the reasons that caused me to create my course and book, where I show how you can develop on both Android and iOS platforms using Kotlin and Swift, create the same architecture with using native approaches tools.

Thank you for reading. If you are interested in improving your mobile development skills, take a look on my site.