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

Kotlin In-depth [Vol-II]

A comprehensive guide to modern multi-paradigm language

Aleksei Sedunov

Buch teilen
  1. English
  2. ePUB (handyfreundlich)
  3. Über iOS und Android verfügbar
eBook - ePub

Kotlin In-depth [Vol-II]

A comprehensive guide to modern multi-paradigm language

Aleksei Sedunov

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Kotlin In-depth [Vol-II] als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Kotlin In-depth [Vol-II] von Aleksei Sedunov im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Computer Science & Programming in Java. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
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...

Inhaltsverzeichnis