Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Introduction	to	Kotlin	
Coroutines
Async	made	easy
Presented	at	GeekOut 2017
/Roman	Elizarov	@	JetBrains
Speaker:	Roman	Elizarov
• 16+	years	experience
• Previously	developed	high-perf	
trading	software	@	Devexperts
• Teach	con...
Disclaimer
• Most	ideas	presented	herein	are	very	old
• Simula ‘67	was	one	of	the	first	languages	to	
introduce	coroutines...
Why	asynchronous	code?
1
2
3
Can	be	done	with	threads!
Real	need	for	async	when	…
ü You	cannot	afford	threads
• They	are	expensive	to	keep	and	to	switch
• High-load	server-side,...
It	is	all	about	scalability
Classic	async	- callbacks
This	is	simplified.	Handling	
exceptions	makes	it	a	real	mess
callback
async
Obligatory	“callback	hell”	image
Futures/Promises/rx.Single
Propagates	exceptions
promise
composable
No	nesting	indentation
compose
accept
apply
handle
map
flatMap
merge lift
just
supply
CompletableFuture rx.Single
Remembering	all	those	combinato...
Using	Kotlin	coroutines
explicit	coroutine	context
1
2
3
suspending	function natural	signature
Bonus	features
• Regular	loops
• Regular	exception	handing
• Regular	high-level	operators	
• let,	apply,	repeat,	forEach,	...
Blocking	threads
Callbacks
Promises/Futures/Rx
Kotlin	coroutines
How	does	it	work?
A	short	peek	behind	the	scenes
Kotlin	suspending	functions
callback
Kotlin
Java/JVM
Continuation	is	a	generic	callback	interface
Code	with	suspension	points
Kotlin
Java/JVM
Compiles	to	state	machine	
(simplified	code	shown)
Using	coroutines
Get	fun	and	profit
How	to	suspend? Some	3rd party	
callback-based	IO	lib
mark	with	suspend
1
2
3
continuation
4
callback
It	is	ready	to	use	f...
Building	higher-level	functions
Build	higher-level	
abstractions	the	usual	way
mark	with	suspend
Make	it	one-liner	… becau...
A	digression	on	async/await
async function preparePost() {
let request = composeTokenRequest();
let result = await makeReq...
Why	no	await keyword	in	Kotlin?
The	problem	with	async
makeRequest(request) VALID – produces	Promise<Result>
await makeReq...
Kotlin	suspending	functions	
are	designed	to	imitate	
sequential behavior	
by	default	
Concurrency	is	hard
Concurrency	has...
Starting	coroutines
We	need	a	function	that	provides	a	
coroutine	context	for	us.	They	are	
called	coroutine	builders.
One...
Launch
Fire	and	forget!
Returns	immediately,	coroutine	
works	in	background	threads
Context	defines	execution	
policy	(thr...
UI	Context
Just	change	the	context
And	it	gets	executed	on	UI	thread
Coroutines	are	like	
very light-weight	threads
This	coroutine	builder	runs	coroutine	in	
the	context	of	invoker	thread
Lau...
Kotlin	approach	to	async
async function doSomething(): Promise<Result> {
/* ... */
}
Sometimes	you	need the	Promise	and	as...
Recap
• Coroutine	builders
• launch
• runBlocking
• async
• Suspending	functions	with	suspend keyword
• Can	nest	to	any	de...
Wrap	up
Status	and	more
Library	vs	language
• Kotlin	language only	has	suspend keyword
• Transforms	suspend	functions	to	callbacks
• Compiles	code...
Experimental	status	of	coroutines
• This	design	is	new and	unlike	mainstream
• For	some	very	good	reasons
• We	want	commun...
Can	I	use	it	in	production?
Yes!	You	should.
There	is	more
• Channels/Actors
• Selection	and	synchronization
• Job	hierarchies	and	cancellation
• buildSequence/yield
•...
Thank	you
Any	questions?
Slides	are	available	at	www.slideshare.net/elizarov
email	me	to	elizarov at	gmail
relizarov
Introduction to Kotlin coroutines
Introduction to Kotlin coroutines
Upcoming SlideShare
Loading in …5
×

Introduction to Kotlin coroutines

3,643 views

Published on

Presented on GeekOut 2017 conference. Video is here: https://vimeo.com/221264980

Published in: Technology

Introduction to Kotlin coroutines

  1. 1. Introduction to Kotlin Coroutines Async made easy Presented at GeekOut 2017 /Roman Elizarov @ JetBrains
  2. 2. Speaker: Roman Elizarov • 16+ years experience • Previously developed high-perf trading software @ Devexperts • Teach concurrent & distributed programming @ St. Petersburg ITMO University • Chief judge @ Northeastern European Region of ACM ICPC • Now work on Kotlin @ JetBrains
  3. 3. Disclaimer • Most ideas presented herein are very old • Simula ‘67 was one of the first languages to introduce coroutines • detach – was a coroutine suspension statement • resume – was to resume coroutine execution • CLU ‘75 was the first language with generators and Icon ‘77 was prominently using them • Coroutines fell out of favor due to emergence of multithreading • And now they are back to write asynchronous code
  4. 4. Why asynchronous code? 1 2 3 Can be done with threads!
  5. 5. Real need for async when … ü You cannot afford threads • They are expensive to keep and to switch • High-load server-side, micro-tasks, etc ü You cannot do threads • You code is single thread only • JS/web target, μC, etc ü You do not want threads • You have lot of mutable state • Mobile/Desktop UI apps, etc
  6. 6. It is all about scalability
  7. 7. Classic async - callbacks This is simplified. Handling exceptions makes it a real mess callback async
  8. 8. Obligatory “callback hell” image
  9. 9. Futures/Promises/rx.Single Propagates exceptions promise composable No nesting indentation
  10. 10. compose accept apply handle map flatMap merge lift just supply CompletableFuture rx.Single Remembering all those combinators onEach
  11. 11. Using Kotlin coroutines explicit coroutine context 1 2 3 suspending function natural signature
  12. 12. Bonus features • Regular loops • Regular exception handing • Regular high-level operators • let, apply, repeat, forEach, filter, map, use, etc Everything like in blocking code
  13. 13. Blocking threads Callbacks Promises/Futures/Rx Kotlin coroutines
  14. 14. How does it work? A short peek behind the scenes
  15. 15. Kotlin suspending functions callback Kotlin Java/JVM Continuation is a generic callback interface
  16. 16. Code with suspension points Kotlin Java/JVM Compiles to state machine (simplified code shown)
  17. 17. Using coroutines Get fun and profit
  18. 18. How to suspend? Some 3rd party callback-based IO lib mark with suspend 1 2 3 continuation 4 callback It is ready to use from coroutines! Inspired by call/cc from Scheme
  19. 19. Building higher-level functions Build higher-level abstractions the usual way mark with suspend Make it one-liner … because Kotlin!
  20. 20. A digression on async/await async function preparePost() { let request = composeTokenRequest(); let result = await makeRequest(request); return result.parseToken(); } async function preparePost(): Promise<Token> { let request = composeTokenRequest(); let result = await makeRequest(request); return result.parseToken(); } JS approach to the same problem (also TS, C#, Dart, etc) mark with async use await to suspend JS
  21. 21. Why no await keyword in Kotlin? The problem with async makeRequest(request) VALID – produces Promise<Result> await makeRequest(request) VALID – produces Result concurrent & async behavior sequential behavior The most needed one, yet the most syntactically clumsy, esp. for suspend-heavy (CSP) code style
  22. 22. Kotlin suspending functions are designed to imitate sequential behavior by default Concurrency is hard Concurrency has to be explicit
  23. 23. Starting coroutines We need a function that provides a coroutine context for us. They are called coroutine builders. One cannot simply invoke a suspending function
  24. 24. Launch Fire and forget! Returns immediately, coroutine works in background threads Context defines execution policy (thread pool)
  25. 25. UI Context Just change the context And it gets executed on UI thread
  26. 26. Coroutines are like very light-weight threads This coroutine builder runs coroutine in the context of invoker thread Launch returns Job object We can join to a job just like to a thread 1 2 Try that with 100k threads!
  27. 27. Kotlin approach to async async function doSomething(): Promise<Result> { /* ... */ } Sometimes you need the Promise and async let request1 = doSomething(); let request2 = doSomething(); 1 2 To start multiple operations concurrently await request1; await request2; JS and then wait for them async builder await function Returns Deferred<Result> Suspends until deferred is complete
  28. 28. Recap • Coroutine builders • launch • runBlocking • async • Suspending functions with suspend keyword • Can nest to any depth (not stackless) • suspendCoroutine Regular world Coroutine Coroutine Callback Coroutine Coroutine
  29. 29. Wrap up Status and more
  30. 30. Library vs language • Kotlin language only has suspend keyword • Transforms suspend functions to callbacks • Compiles code to state machines • stdlib has Continuation and CoroutineContext • Everything else is in a library • It includes launch/join, async/await, runBlocking, etc • We were using kotlinx.coroutines library • http://github.com/kotlin/kotlinx.coroutines • You can study source and contribute It is designed to be composable Mix & match different libs
  31. 31. Experimental status of coroutines • This design is new and unlike mainstream • For some very good reasons • We want community to try it for real • So we released it as an experimental feature • We guarantee backwards compatibility • Old code compiled with coroutines continues to work • We reserve the right to break forward compatibility • We may add things so new code may not run w/old RT • Design will be finalized at a later point • Old code will continue to work via support library • Migration aids to the final design will be provided opt-in flag
  32. 32. Can I use it in production? Yes! You should.
  33. 33. There is more • Channels/Actors • Selection and synchronization • Job hierarchies and cancellation • buildSequence/yield • Restricted (sync) suspension • Interop with other futures/promise/reactive libs • The actual implementation details • Learn more in Guide to kotlinx.coroutines by example • KotlinConf on 2-3 November, 2017 in SF
  34. 34. Thank you Any questions? Slides are available at www.slideshare.net/elizarov email me to elizarov at gmail relizarov

×