SlideShare a Scribd company logo
Coroutines
in Kotlin
September 2017 - Alexey Soshin @ Gett
Kotlin in 1 minute
1. Developed by JetBrains (IntelliJ authors)
2. Powers all JetBrains tools
3. Open source
4. 100% interoperable with Java
5. First class citizen language on Android
6. Awesome modern language
7. Provides
a. Null safety
Concurrency
Think of concurrency as “Being able to do something else while you wait”
Concurrency suddenly matters, because modern systems spend a lot of their time on waiting:
● For memory
● For network
● For disk
That’s even before we start considering higher level options such as databases, remote services,
etc
Different concurrency models
● Multi threaded model
● Event loop
○ NodeJS in JavaScript
○ Vertx in Java
● CSP (communicating sequential processes)
○ go and channels in Go
○ Quasar in Java
● Actor model
○ Erlang
Limitations of spawning threads
● Each new Java thread consumes about 1MB of memory
● If we spawn thread for each request, we will eventually run out of available memory
○ Demo
● If we limit number of simultaneously spawned threads, we introduce a non-flexible
bottleneck in our system
○ Demo
Coroutines in Kotlin
● One of the major requirements from a modern language is to have concurrency solution
in place
● Kotlin async/await, channels and actors are not keywords, but simple functions calls
● Library developers are welcome to provide their own coroutines implementation
● JetBrains supply their own implementation as part of KotlinX
● As of Kotlin 1.1 coroutines are still an experimental feature
Starting coroutines and waiting for results
1. val job = async(CommonPool) { ... }
a. Launches coroutine that returns a result
2. val job = launch(CommonPool) { … }
a. Launches coroutine that doesn’t return any result (background job)
3. job.join()
a. Tells current coroutine to wait for job to execute
4. val result = job.await()
a. Tells current coroutine to wait, and returns its result
b. Example
Coroutines limitations
1. Since behind the scenes coroutines depend on event loop, coroutine that is CPU bound
may not let other coroutines execute
2. This may result in starvation
a. Example
Thread 1: coroutine 1
...
Thread 4: coroutine 4
coroutine 5 coroutine 6 Waiting...
Let it go: yield()
1. yield()
a. Resolves aforementioned problem by giving control back to the coroutine scheduler
b. This is only necessary if you don’t have calls to other suspending methods
c. Example
coroutine 4 continuesThread 4: coroutine 4 => yield coroutine 5
Cancelling coroutines
1. How do you cancel a running task in Java?
a. Hint: Future.cancel() may not work
b. Hint: pool.shutdownNow() may not work
c. Read more
2. Kotlin: job.cancel()
a. Asks nicely to cancel currently running coroutine
b. As in previous example, if coroutine never suspends, it cannot be cancelled.
Handling timeouts
1. How do you set a timeout for a Thread in Java
a. Hint: Same as cancel(), won’t always work as you expect
b. Read more
2. Kotlin: withTimeout(time, unit) { … }
a. While in context of coroutine, will throw TimeoutException if timeout has been reached, and
coroutine didn’t produce any results yet
b. Example
Coroutines hierarchy
1. Up until now we supplied CommonPool as the only argument for coroutine builder
function
a. async(CommonPool)
b. launch(CommonPool)
2. But builders also receive other arguments
3. For example, you can specify parent coroutine, that will able to cancel simultaneosly all
coroutines underneath it:
a. async(CommonPool + parentJob)
b. Example
Producers
1. produce(CommonPool) { … }
a. Will create a coroutine with outbound channel
b. Channel is a stream of values produced by the coroutine
2. select { … }
a. Lets you listen to numerous outbound channels, and act accordingly
b. select is a expression, so getting its value is simple:
i. val result = select { … }
c. Example
Actors
1. actor<String>(CommonPool, capacity = 100) { … }
a. Like producers, actors are coroutines bound to a channel
b. This time the channel is inbound. You have a clear way to send messages to actor, but how do you
get answers is up to you
c. That’s unlike some other Actor implementations, where actor has both inbound and outbound
mailboxes
d. Also, note that in Kotlin, the mailbox is bounded by capacity
e. Example
Questions?
Reading material
https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md
https://kotlinlang.org/docs/tutorials/coroutines-basic-jvm.html
https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md
https://blog.simon-wirtz.de/kotlin-coroutines-guide/
Examples: https://github.com/AlexeySoshin/KotlinCoroutinesIntro
Follow me
https://github.com/alexeysoshin
https://medium.com/@alexey.soshin/
https://stackoverflow.com/users/5985853/alexey-soshin
https://www.quora.com/profile/Alexey-Soshin
Or simply reach out by email: alexey.soshin@gmail.com

More Related Content

What's hot

Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017
Roman Elizarov
 
Kotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a treeKotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a tree
Kai Koenig
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
Christian Melchior
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
Dariusz Lorenc
 
Android with kotlin course
Android with kotlin courseAndroid with kotlin course
Android with kotlin course
Abdul Rahman Masri Attal
 
Android kotlin coroutines
Android kotlin coroutinesAndroid kotlin coroutines
Android kotlin coroutines
Bipin Vayalu
 
Jetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIJetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UI
Gilang Ramadhan
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
NAVER Engineering
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android application
Seven Peaks Speaks
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
XPeppers
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
MobileAcademy
 
JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013
Vladimir Ivanov
 
What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How? What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How?
Shady Selim
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
Simplilearn
 
Kotlin Coroutines Reloaded
Kotlin Coroutines ReloadedKotlin Coroutines Reloaded
Kotlin Coroutines Reloaded
Roman Elizarov
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
Yura Nosenko
 
Android Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUKAndroid Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUK
Fabio Collini
 
Kotlin Multiplatform
Kotlin MultiplatformKotlin Multiplatform
Kotlin Multiplatform
Kevin Galligan
 
Introduction To Java.
Introduction To Java.Introduction To Java.
Introduction To Java.
Tushar Chauhan
 

What's hot (20)

Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017
 
Kotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a treeKotlin Coroutines and Android sitting in a tree
Kotlin Coroutines and Android sitting in a tree
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Android with kotlin course
Android with kotlin courseAndroid with kotlin course
Android with kotlin course
 
Android kotlin coroutines
Android kotlin coroutinesAndroid kotlin coroutines
Android kotlin coroutines
 
Jetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UIJetpack Compose - Android’s modern toolkit for building native UI
Jetpack Compose - Android’s modern toolkit for building native UI
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android application
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
 
JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013
 
What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How? What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How?
 
Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022Kotlin InDepth Tutorial for beginners 2022
Kotlin InDepth Tutorial for beginners 2022
 
Kotlin Coroutines Reloaded
Kotlin Coroutines ReloadedKotlin Coroutines Reloaded
Kotlin Coroutines Reloaded
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Android Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUKAndroid Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUK
 
Kotlin Multiplatform
Kotlin MultiplatformKotlin Multiplatform
Kotlin Multiplatform
 
Introduction To Java.
Introduction To Java.Introduction To Java.
Introduction To Java.
 

Similar to Coroutines in Kotlin

Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
Ruben Inoto Soto
 
Quick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android DevQuick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android Dev
Shuhei Shogen
 
Asynchronous programming intro
Asynchronous programming introAsynchronous programming intro
Asynchronous programming intro
cc liu
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
Paul Churchward
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
Ahmed Misbah
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!
C4Media
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
Demystifying the Go Scheduler
Demystifying the Go SchedulerDemystifying the Go Scheduler
Demystifying the Go Scheduler
matthewrdale
 
04 threads
04 threads04 threads
04 threads
ambar khetan
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
Fundamental concurrent programming
Fundamental concurrent programmingFundamental concurrent programming
Fundamental concurrent programming
Dimas Prawira
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
Squareboat
 
Design patterns with kotlin
Design patterns with kotlinDesign patterns with kotlin
Design patterns with kotlin
Alexey Soshin
 
droidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutinesdroidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutines
Arthur Nagy
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
priyank09
 
Java On CRaC
Java On CRaCJava On CRaC
Java On CRaC
Simon Ritter
 
Introduction to Kotlin for Java developer
Introduction to Kotlin for Java developerIntroduction to Kotlin for Java developer
Introduction to Kotlin for Java developer
Shuhei Shogen
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
Carol McDonald
 

Similar to Coroutines in Kotlin (20)

Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Quick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android DevQuick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android Dev
 
Asynchronous programming intro
Asynchronous programming introAsynchronous programming intro
Asynchronous programming intro
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Demystifying the Go Scheduler
Demystifying the Go SchedulerDemystifying the Go Scheduler
Demystifying the Go Scheduler
 
04 threads
04 threads04 threads
04 threads
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Fundamental concurrent programming
Fundamental concurrent programmingFundamental concurrent programming
Fundamental concurrent programming
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Design patterns with kotlin
Design patterns with kotlinDesign patterns with kotlin
Design patterns with kotlin
 
droidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutinesdroidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutines
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Java On CRaC
Java On CRaCJava On CRaC
Java On CRaC
 
Introduction to Kotlin for Java developer
Introduction to Kotlin for Java developerIntroduction to Kotlin for Java developer
Introduction to Kotlin for Java developer
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 

Recently uploaded

Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
Anand Bagmar
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual PerfectionBuilding the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Applitools
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdfTheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
Ortus Solutions, Corp
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
kalichargn70th171
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
Softradix Technologies
 
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
manji sharman06
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
The Ultimate Guide to Top 36 DevOps Testing Tools for 2024.pdf
The Ultimate Guide to Top 36 DevOps Testing Tools for 2024.pdfThe Ultimate Guide to Top 36 DevOps Testing Tools for 2024.pdf
The Ultimate Guide to Top 36 DevOps Testing Tools for 2024.pdf
kalichargn70th171
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
Michał Kurzeja
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
kalichargn70th171
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
jrodriguezq3110
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 

Recently uploaded (20)

Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual PerfectionBuilding the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdfTheFutureIsDynamic-BoxLang-CFCamp2024.pdf
TheFutureIsDynamic-BoxLang-CFCamp2024.pdf
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
 
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
Call Girls Bangalore🔥7023059433🔥Best Profile Escorts in Bangalore Available 24/7
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
The Ultimate Guide to Top 36 DevOps Testing Tools for 2024.pdf
The Ultimate Guide to Top 36 DevOps Testing Tools for 2024.pdfThe Ultimate Guide to Top 36 DevOps Testing Tools for 2024.pdf
The Ultimate Guide to Top 36 DevOps Testing Tools for 2024.pdf
 
Refactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contextsRefactoring legacy systems using events commands and bubble contexts
Refactoring legacy systems using events commands and bubble contexts
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
What is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdfWhat is Continuous Testing in DevOps - A Definitive Guide.pdf
What is Continuous Testing in DevOps - A Definitive Guide.pdf
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 

Coroutines in Kotlin

  • 1. Coroutines in Kotlin September 2017 - Alexey Soshin @ Gett
  • 2. Kotlin in 1 minute 1. Developed by JetBrains (IntelliJ authors) 2. Powers all JetBrains tools 3. Open source 4. 100% interoperable with Java 5. First class citizen language on Android 6. Awesome modern language 7. Provides a. Null safety
  • 3. Concurrency Think of concurrency as “Being able to do something else while you wait” Concurrency suddenly matters, because modern systems spend a lot of their time on waiting: ● For memory ● For network ● For disk That’s even before we start considering higher level options such as databases, remote services, etc
  • 4. Different concurrency models ● Multi threaded model ● Event loop ○ NodeJS in JavaScript ○ Vertx in Java ● CSP (communicating sequential processes) ○ go and channels in Go ○ Quasar in Java ● Actor model ○ Erlang
  • 5. Limitations of spawning threads ● Each new Java thread consumes about 1MB of memory ● If we spawn thread for each request, we will eventually run out of available memory ○ Demo ● If we limit number of simultaneously spawned threads, we introduce a non-flexible bottleneck in our system ○ Demo
  • 6. Coroutines in Kotlin ● One of the major requirements from a modern language is to have concurrency solution in place ● Kotlin async/await, channels and actors are not keywords, but simple functions calls ● Library developers are welcome to provide their own coroutines implementation ● JetBrains supply their own implementation as part of KotlinX ● As of Kotlin 1.1 coroutines are still an experimental feature
  • 7. Starting coroutines and waiting for results 1. val job = async(CommonPool) { ... } a. Launches coroutine that returns a result 2. val job = launch(CommonPool) { … } a. Launches coroutine that doesn’t return any result (background job) 3. job.join() a. Tells current coroutine to wait for job to execute 4. val result = job.await() a. Tells current coroutine to wait, and returns its result b. Example
  • 8. Coroutines limitations 1. Since behind the scenes coroutines depend on event loop, coroutine that is CPU bound may not let other coroutines execute 2. This may result in starvation a. Example Thread 1: coroutine 1 ... Thread 4: coroutine 4 coroutine 5 coroutine 6 Waiting...
  • 9. Let it go: yield() 1. yield() a. Resolves aforementioned problem by giving control back to the coroutine scheduler b. This is only necessary if you don’t have calls to other suspending methods c. Example coroutine 4 continuesThread 4: coroutine 4 => yield coroutine 5
  • 10. Cancelling coroutines 1. How do you cancel a running task in Java? a. Hint: Future.cancel() may not work b. Hint: pool.shutdownNow() may not work c. Read more 2. Kotlin: job.cancel() a. Asks nicely to cancel currently running coroutine b. As in previous example, if coroutine never suspends, it cannot be cancelled.
  • 11. Handling timeouts 1. How do you set a timeout for a Thread in Java a. Hint: Same as cancel(), won’t always work as you expect b. Read more 2. Kotlin: withTimeout(time, unit) { … } a. While in context of coroutine, will throw TimeoutException if timeout has been reached, and coroutine didn’t produce any results yet b. Example
  • 12. Coroutines hierarchy 1. Up until now we supplied CommonPool as the only argument for coroutine builder function a. async(CommonPool) b. launch(CommonPool) 2. But builders also receive other arguments 3. For example, you can specify parent coroutine, that will able to cancel simultaneosly all coroutines underneath it: a. async(CommonPool + parentJob) b. Example
  • 13. Producers 1. produce(CommonPool) { … } a. Will create a coroutine with outbound channel b. Channel is a stream of values produced by the coroutine 2. select { … } a. Lets you listen to numerous outbound channels, and act accordingly b. select is a expression, so getting its value is simple: i. val result = select { … } c. Example
  • 14. Actors 1. actor<String>(CommonPool, capacity = 100) { … } a. Like producers, actors are coroutines bound to a channel b. This time the channel is inbound. You have a clear way to send messages to actor, but how do you get answers is up to you c. That’s unlike some other Actor implementations, where actor has both inbound and outbound mailboxes d. Also, note that in Kotlin, the mailbox is bounded by capacity e. Example