article banner

Exercise: UserDownloader

This UserDownloader class is used to fetch users from an API, followed by a list of all downloaded users. The problem is that it is not thread-safe; therefore, when you use the getUser function from multiple coroutines, you will have concurrency problems and the list of downloaded users will not be complete. Fix this problem using the following techniques:

  • Use a dispatcher limited to a single thread and use a read-only list to store users.
  • Use a dispatcher limited to a single thread and keep using a mutable list to store users.
  • Use a synchronized block to protect the shared state and keep using a mutable list to store users.
  • Use a concurrent collection to store users.
class UserDownloader(private val api: NetworkService) { private val users = mutableListOf<User>() fun downloaded(): List<User> = users.toList() suspend fun getUser(id: Int) { val newUser = api.getUser(id) users += newUser } }

This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in effective/safe/Downloader.kt. You can find there starting code and unit tests.

Once you are done with the exercise, you can check your solution here.

Playground

import kotlinx.coroutines.* import org.junit.Test import kotlin.test.assertEquals data class User(val name: String) interface NetworkService { suspend fun getUser(id: Int): User } class FakeNetworkService : NetworkService { override suspend fun getUser(id: Int): User { delay(2) return User("User$id") } } class UserDownloader(private val api: NetworkService) { private val users = mutableListOf<User>() fun downloaded(): List<User> = users.toList() suspend fun getUser(id: Int) { val newUser = api.getUser(id) users += newUser } } suspend fun main(): Unit = coroutineScope { val downloader = UserDownloader(FakeNetworkService()) coroutineScope { repeat(1_000_000) { launch { downloader.getUser(it) } } } print(downloader.downloaded().size) // ~714725 } class UserDownloaderTest { @Test fun test() = runBlocking { val downloader = UserDownloader(FakeNetworkService()) coroutineScope { repeat(1_000_000) { launch(Dispatchers.Default) { downloader.getUser(it) } } } assertEquals(1_000_000, downloader.downloaded().size) } }