Learning Concurrency in Kotlin

Book description

Take advantage of Kotlin's concurrency primitives to write efficient multithreaded applications

Key Features

  • Learn Kotlin's unique approach to multithreading
  • Work through practical examples that will help you write concurrent non-blocking code
  • Improve the overall execution speed in multiprocessor and multicore systems

Book Description

The primary requirements of modern-day applications are scalability, speed, and making the most use of hardware. Kotlin meets these requirements with its immense support for concurrency. Many concurrent primitives of Kotlin, such as channels and suspending functions, are designed to be non-blocking and efficient. This allows for new approaches to concurrency and creates unique challenges for the design and implementation of concurrent code. Learning Concurrency in Kotlin addresses those challenges with real-life examples and exercises that take advantage of Kotlin's primitives. Beginning with an introduction to Kotlin's coroutines, you will learn how to write concurrent code and understand the fundamental concepts needed to be able to write multithreaded software in Kotlin. You'll explore how to communicate between and synchronize your threads and coroutines to write asynchronous applications that are collaborative. You'll also learn how to handle errors and exceptions, as well as how to leverage multi-core processing. In addition to this, you'll delve into how coroutines work internally, allowing you to see the bigger picture. Throughout the book you'll build an Android application – an RSS reader – designed and implemented according to the different topics covered in the book

What you will learn

  • Understand Kotlin's approach to concurrency
  • Implement sequential and asynchronous suspending functions
  • Create suspending data sources that are resumed on demand
  • Explore the best practices for error handling
  • Use channels to communicate between coroutines
  • Uncover how coroutines work under the hood

Who this book is for

If you're a Kotlin or Android developer interested in learning how to program concurrently to enhance the performance of your applications, this is the book for you.

Downloading the example code for this book You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Publisher resources

Download Example Code

Table of contents

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

Product information

  • Title: Learning Concurrency in Kotlin
  • Author(s): Miguel Angel Castiblanco Torres
  • Release date: July 2018
  • Publisher(s): Packt Publishing
  • ISBN: 9781788627160