Kotlin In-depth [Vol-II]
eBook - ePub

Kotlin In-depth [Vol-II]

A comprehensive guide to modern multi-paradigm language

Aleksei Sedunov

Share book
  1. English
  2. ePUB (mobile friendly)
  3. Available on iOS & Android
eBook - ePub

Kotlin In-depth [Vol-II]

A comprehensive guide to modern multi-paradigm language

Aleksei Sedunov

Book details
Book preview
Table of contents
Citations

About This Book

Master the concise and expressive power of a pragmatic multi-paradigm language for JVM, Android and beyond Key Features

  • Language fundamentals
  • Object-oriented and functional programming with Kotlin
  • Kotlin standard library
  • Building domain-specific languages
  • Using Kotlin for Web development
  • Kotlin for Android platform
  • Coroutine-based concurrency

  • Description
    The purpose of this book is to guide a reader through the capabilities of the Kotlin language and give examples of using it for development of various applications be it desktop, mobile or Web. Although our primary focus is on the JVM and Android, the knowledge we're sharing here to various extents applies to other Kotlin-supported platforms such as JavaScript, native and even multi-platform applications.The book starts with an introduction to language and its ecosystem that will give you an understanding of the key ideas behind Kotlin design, introduce you to the Kotlin tooling and present you the basic language syntax and constructs. In the next chapters we'll get to know the multi-paradigm nature of Kotlin which allows you to create powerful abstractions by combining various aspects of functional and object-oriented programming. We'll talk about using common Kotlin APIs such as the standard library, reflection, and coroutine-based concurrency as well as the means for creating your own flexible APIs based on domain-specific languages. In the concluding chapters, we'll give examples of using Kotlin for more specialized tasks such as testing, building Android applications, Web development and creating microservices.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Kotlin In-depth [Vol-II] an online PDF/ePUB?
Yes, you can access Kotlin In-depth [Vol-II] by Aleksei Sedunov in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in Java. We have over one million books available in our catalogue for you to explore.

Information

Year
2020
ISBN
9789389423228

CHAPTER 13

Concurrency

In this chapter, we will focus on a major topic of writing concurrent code. Our main goal will be to get an understanding of coroutines; one of the distinguishing features of Kotlin, first introduced in version 1.1 and achieving release status in Kotlin 1.3.
We’ll start with the discussion of basic ideas underlying Kotlin coroutines such as suspending functions and structured complexity and then gradually move to more advanced issues of concurrent control-flow, how the coroutine state changes throughout its lifecycle, how cancellation and exception work, and how concurrent tasks get assigned to threads.
We will also cover techniques such as channels and actors which allow your code to implement communication between concurrent tasks and to share some mutable data in a thread-safe manner.
In conclusion, we’ll also discuss some utilities simplifying the usage of the Java concurrency API in the Kotlin code, creating threads, and using synchronization and locks.

Structure

  • Coroutines
  • Concurrent communication
  • Using Java concurrency

Objective

To learn using concurrency primitives provided by the Kotlin coroutines library for building scalable and responsive code.

Coroutines

Kotlin programs can easily use Java concurrent primitives to achieve thread safety. Using them, however, still poses a certain problem because most concurrent operations are blocking; in other words, a thread which uses operations such as Thread.sleep(), Thread.join() or Object.wait() will be blocked until its execution is completed. Blocking and resuming thread execution requires computationally intensive context switching at the system level which may negatively impact program performance. On top of that, each thread consumes a considerable amount of system resources so maintaining a large number of concurrent threads may be impractical or even not possible at all.
A more efficient approach involves asynchronous programming. We can supply a lambda which is to be called back when the requested operation is completed. The original thread in the meantime can go on with some useful work (like processing client requests or handling UI events) instead of just waiting in a blocked state. The major problem of such an approach is a drastic increase of code complexity as we can’t use an ordinary imperative control-flow.
In Kotlin, you can have the best of both worlds; thanks to a powerful mechanism of coroutines which allows you to write code in a familiar imperative style and yet have it automatically transformed into an efficient asynchronous computation by compiler. This mechanism is based on the concept of suspending functions which are able to preserve their context and may be suspended and resumed at certain points of their execution.
It’s worth noting that most of the coroutines power is provided by a separate library which must be explicitly configured in your project. The version used in the book is given by the following Maven coordinates: org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.2.
IDE Tips: If you’re using IntelliJ IDEA without relying on any particular build system like Maven or Gradle, you can add the coroutines library by following the given steps:
  1. Press F4 on the root node in the Project View panel or right click on it and choose Open Module Settings.
  2. Click on the Libraries item on the left, then click on the + button on the top toolbar and choose the From Maven
 option.
  3. Type the Maven coordinates of the library (e.g. org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.2) and click OK (as shown in Figure 13.1).
  4. The IDE will then download the library with the necessary dependencies and suggest adding it to modules of your project. Confirm it by clicking on OK.
Figure 13.1: Downloading Kotlin coroutines library
In the following sections, we’ll talk about the basic concepts introduced by the coroutines library and see how they can be used for the purpose of concurrent programming.

Coroutines and suspending functions

The basic language primitive underlying the entire coroutines library is a suspending function. This is generalization of an ordinary function which has the ability to suspend its execution on certain points in its body retaining all the necessary context and then resume on demand. In Kotlin, such functions are marked by the suspend modifier:
suspend fun foo() {
println("Task started")
delay(100)
println("Task finished")
}
The delay() function we’ve used is a suspending function defined in the coroutines library. Its purpose is similar to the Thread.sleep(); however, instead of blocking the current thread, it suspends the calling function leaving the thread free for execution of other tasks (such as switching to the other suspending function).
Suspending functions may call both suspending and ordinary functions. In the former case, such a call becomes a suspension point where the caller execution may be temporarily stopped and resumed later, while the latter proceeds just like a normal function call which returns after the invoked function has finished. Kotlin, however, forbids calling suspending functions from an ordinary one:
fun foo() {
println("Task started")
delay(100) // Error: delay is a suspend function
println("Task finished")
}
IDE Tips: When using the IntelliJ plugin, you can easily distinguish the suspending call by a special icon on the left of the corresponding line as shown in Figure 13.1:
Figure 13.2: Suspending calls in IDE
If only suspending functions are allowed to make suspending calls, how do we invoke a suspending function at all? The most obvious way to is to mark the main() function itself as suspend:
import kotlinx.coroutines.delay
suspend fun main() {
println("Task...

Table of contents