The Problem with Shared State
Explore the challenges of managing shared mutable state in Kotlin coroutines, including issues like data conflicts and thread safety problems. Understand why traditional blocking synchronization is inefficient in coroutines, and learn how to use atomic operations and coroutine-specific tools to safely handle concurrent state modifications without blocking threads.
We'll cover the following...
Before we start, take a look at the UserDownloader class below. It allows us to fetch a user by ID or get all the users downloaded before. What’s wrong with this implementation?
Note: Notice the use of the defensive copy
toList. We did this to avoid a conflict between reading the object returned bydownloadedand adding an element to the mutable list. We could also represent users using the read-only list (List<User>) and the read-write property (var). Then, we would not need to make a defensive copy, anddownloadedwould not need to be protected at all, but we would decrease the performance of adding elements to the collection. We prefer the second approach, but we’ve decided to show the one using a mutable collection as we see it more often in real-life projects. ...