Title Page Copyright and Credits Learning Concurrency in Kotlin Packt Upsell Why subscribe? PacktPub.com Contributors About the author About the reviewer Packt is searching for authors like you Preface Who this book is for What this book covers To get the most out of this book Download the example code files Conventions used Get in touch Reviews Hello, Concurrent World! Processes, threads, and coroutines Processes Threads Coroutines Putting things together Introduction to concurrency Concurrency is not parallelism CPU-bound and I/O-bound CPU-bound I/O-bound Concurrency versus parallelism in CPU-bound algorithms Single-core execution Parallel execution Concurrency versus parallelism in I/O-bound algorithms Why concurrency is often feared Race conditions Atomicity violation Deadlocks Livelocks Concurrency in Kotlin Non-blocking Being explicit Readable Leveraged Flexible Concepts and terminology Suspending computations Suspending functions Suspending lambdas Coroutine dispatcher Coroutine builders Summary Coroutines in Action Downloading and installing Android Studio Creating a Kotlin project Adding support for coroutines Android's UI thread CalledFromWrongThreadException NetworkOnMainThreadException Requesting in the background, updating in the UI thread Creating a thread CoroutineDispatcher Attaching a coroutine to a dispatcher Starting a coroutine with async Starting a coroutine with launch Using a specific dispatcher when starting the coroutine Adding networking permissions Creating a coroutine to call a service Adding UI elements What happens when the UI is blocked Displaying the amount of news that were processed Using a UI dispatcher Platform-specific UI libraries Adding the dependency Using Android's UI coroutine dispatcher Creating an asynchronous function to hold the request... or not A synchronous function wrapped in an asynchronous caller An asynchronous function with a predefined dispatcher An asynchronous function with a flexible dispatcher How to decide which option is better Summary Life Cycle and Error Handling Job and Deferred Job Exception handling Life cycle New Active Canceling Cancelled Completed Determining the current state of a Job Deferred Exception handling States move in one direction only A note on final states RSS – Reading from multiple feeds concurrently Supporting a list of feeds Creating a thread pool Fetching the data concurrently Merging the responses Testing the concurrent requests Non-happy path – Unexpected crash Having deferred store the exception Don't ignore the exception! Summary Suspending Functions and the Coroutine Context Improving the UI of the RSS Reader Giving each feed a name Fetching more information about the articles from the feed Adding a scrollable list for the articles Layout for the individual articles Adapter to map the information Adding a ViewHolder Mapping the data onCreateViewHolder onBindViewHolder getItemCount Allowing the incremental addition of articles to the adapter Connecting the adapter to the activity Testing the new UI Sanitizing the data Suspending functions Suspending functions in action Writing a repository with async functions Upgrading to suspending functions Suspending functions versus async functions The coroutine context Dispatcher CommonPool Default dispatcher Unconfined Single thread context Thread pool Exception handling Non-cancellable More about contexts Mixing contexts Combining contexts Separating contexts Temporary context switch using withContext Summary Iterators, Sequences, and Producers Suspendable sequences and iterators Yielding values Iterators Interacting with an iterator Going through all the elements Getting the next value Validating whether there are more elements Calling next() without validating for elements A note on the inner working of hasNext() Sequences Interacting with a sequence Reading all the elements in the sequence Obtaining a specific element elementAt elementAtOrElse elementAtOrNull Obtaining a group of elements Sequences are stateless Suspending Fibonacci Writing a Fibonacci sequence Writing a Fibonnaci iterator Producers Creating a producer Interacting with a producer Reading all the elements in the producer Receiving a single element Taking a group of elements Taking more elements than those available Suspending a Fibonacci sequence using a producer Producers in action Having the adapter request more articles Creating a producer that fetches feeds on demand Adding the articles to the list on the UI Summary Channels - Share Memory by Communicating Understanding channels Use case – streaming data Use case – distributing work Types of channels and backpressure Unbuffered channels RendezvousChannel Buffered channels LinkedListChannel ArrayChannel ConflatedChannel Interacting with channels SendChannel Validating before sending Sending elements Offering elements On channel closed On channel full On channel open and not full ReceiveChannel Validating before reading isClosedForReceive isEmpty Channels in action Adding a search activity Adding the search function Implementing the collaborative search Connecting the search functions Updating ArticleAdapter Displaying the results Summary Thread Confinement, Actors, and Mutexes Atomicity violation What atomicity means Thread confinement What is thread confinement? Confining coroutines to a single thread Actors What is an actor? Creating an actor Using actors to extend the functionality More on actor interaction Buffered actors Actor with CoroutineContext CoroutineStart Mutual exclusions Understanding mutual exclusions Creating mutexes Interacting with mutual exclusions Volatile variables Thread cache @Volatile Why @Volatile doesn't solve thread-safe counters When to use @Volatile Atomic data structures Actors in action Adding the label to the UI Creating an actor to use as a counter Increasing the counter as results are loaded Adding a channel so that the UI reacts to updates Sending the updated value through the channel Updating the UI on changes Testing the implementation Extending the actor to allow for resetting the counter Resetting the counter upon new searches Summary Testing and Debugging Concurrent Code Testing concurrent code Throwing away assumptions Focus on the forest, not the trees Writing Functional Tests More advice on tests Writing the tests Creating a flawed UserManager Adding the kotlin-test library Adding a happy path test Testing for an edge case Identifying the issue Fixing the crash Retesting Debugging Identifying a coroutine in the logs Using automatic naming Setting a specific name Identifying a coroutine in the debugger Adding a debugger watch Conditional breakpoint Resiliency and stability Summary The Internals of Concurrency in Kotlin Continuation Passing Style Continuations The suspend modifier State machine Labels Continuations Callbacks Incrementing the label Storing the result from the other operations Returning the result of the suspending computation Context switching Thread switching ContinuationInterceptor CoroutineDispatcher CommonPool Unconfined Android's UI DispatchedContinuation DispatchedTask Recap Exception handling The handleCoroutineException() function CoroutineExceptionHandler CancellationException Cancelling the job Platform specific logic JVM JavaScript Summary Other Books You May Enjoy Leave a review - let other readers know what you think