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

Kotlin In-depth [Vol-II]

A comprehensive guide to modern multi-paradigm language

Aleksei Sedunov

Condividi libro
  1. English
  2. ePUB (disponibile sull'app)
  3. Disponibile su iOS e Android
eBook - ePub

Kotlin In-depth [Vol-II]

A comprehensive guide to modern multi-paradigm language

Aleksei Sedunov

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Kotlin In-depth [Vol-II] è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Kotlin In-depth [Vol-II] di Aleksei Sedunov in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in Java. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

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

Indice dei contenuti