SlideShare a Scribd company logo
1 of 38
Download to read offline
Corou%nes	
  in	
  Kotlin	
  
Andrey.Breslav@JetBrains.com	
  
This	
  talk	
  could	
  have	
  been	
  named…	
  
•  async/await/yield	
  
•  fibers	
  
•  [stackless]	
  con%nua%ons	
  
Suspendable	
  
Computa%ons	
  
Outline	
  
•  Mo%va%on/Examples	
  
•  Solu%ons	
  in	
  other	
  languages	
  
•  Kotlin’s	
  Solu%on	
  
–  Client	
  code	
  
–  Library	
  code	
  
•  Compiling	
  Corou%nes	
  
•  Excep%on	
  Handling	
  
•  Appendix.	
  Serializable	
  Corou%nes?	
  
“Legal”	
  
•  All	
  I’m	
  saying	
  is	
  no	
  more	
  final	
  than	
  Valhalla	
  J	
  
 
val	
  image	
  =	
  loadImage(url)	
  
myUI.setImage(image)	
  
	
  
Mo%va%on	
  
Time-­‐consuming	
  
opera%on	
  
UI	
  Thread	
  
Latency!	
  
•  Blocking	
  bad.	
  Very	
  bad.	
  
asyncUI	
  {	
  
val	
  image	
  =	
  await(loadImage(url))	
  
myUI.setImage(image)	
  
}	
  
Suspendable	
  Computa%on	
  
Suspending	
  
call	
  
Con%nua%on	
  
Time-­‐consuming	
  
opera%on	
  
await(…)	
   loadImage(url)	
  
UI	
  Thread	
  
Worker	
  Thread	
  
setImage(…)	
  
“Callback	
  Hell”	
  
Combining	
  Futures	
  
•  CompletableFuture	
  
  .supplyAsync	
  {	
  loadImage(url)	
  }	
  
  .thenAccept(myUI::setImage)	
  
•  so	
  veeery	
  func%onal	
  J	
  
asyncUI	
  {	
  
val	
  image	
  =	
  loadImageAsync(url)	
  
myUI.setImage(image)	
  
}	
  
Flexibility	
  
Asynchronous	
  
opera%on	
  
Con%nua%on	
  
interface	
  Continuation<P>	
  {	
  
	
  	
  	
  	
  fun	
  resume(data:	
  P)	
  
	
  	
  	
  	
  fun	
  resumeWithException(e:	
  Throwable)	
  
}	
  
<Image>	
  
Library	
  Func%on	
  
(corou%ne	
  builder)	
  
asyncUI	
  {	
  
val	
  image	
  =	
  await(loadImage(url))	
  
myUI.setImage(image)	
  
}	
  
Run%me	
  Support	
  
Con%nua%on	
  
interface	
  Continuation<P>	
  {	
  
	
  	
  	
  	
  fun	
  resume(data:	
  P)	
  
	
  	
  	
  	
  fun	
  resumeWithException(e:	
  Throwable)	
  
}	
  
<Image>	
  
Summary:	
  Goals	
  
•  Asynchronous	
  programing	
  (and	
  more)	
  
–  without	
  explicit	
  callbacks	
  
–  without	
  explicit	
  Future	
  combinators	
  
•  Maximum	
  flexibility	
  for	
  library	
  designers	
  
–  with	
  minimal	
  run%me	
  support	
  
–  and	
  no	
  macros	
  J	
  
Flavors	
  of	
  Corou%nes	
  
Stackless	
   Stackful	
  
Language	
  restric;ons	
   Use	
  in	
  special	
  contexts	
  L	
   Use	
  anywhere	
  J	
  
Implemented	
  in	
   C#,	
  Scala,	
  Kotlin,	
  …	
   Quasar,	
  Javaflow,	
  …	
  
Code	
  transforma;on	
   Local	
  (compiler	
  magic)	
  J	
   All	
  over	
  the	
  place	
  L	
  
Run;me	
  support	
   Lidle	
  J	
   Substan%al	
  L	
  
The	
  C#	
  Way	
  
async	
  Task<String>	
  work()	
  {	
  
Thread.sleep(200);	
  
return	
  “done”;	
  
}	
  
	
  
async	
  Task	
  moreWork()	
  {	
  
Console.WriteLine(“Work	
  started”);	
  
var	
  str	
  =	
  await	
  work();	
  
Console.WriteLine($“Work	
  completed:	
  {str}”);	
  
}	
  
Example:	
  async/await	
  (I)	
  
fun work(): CompletableFuture<String> = async {!
Thread.sleep(200)!
"done"!
}!
!
fun moreWork() = async {!
println("Work started")!
val str = await(work())!
println("Work completed: $str")!
}	
  
type	
  is	
  op%onal	
  
Example:	
  async/await	
  (I)	
  
fun work() = async {!
Thread.sleep(200)!
"done"!
}!
!
fun moreWork() = async {!
println("Work started")!
val str = await(work())!
println("Work completed: $str")!
}	
  
await()	
  
fun moreWork() = async {!
println("Work started")!
val str = await(work())!
println("Work completed: $str")!
}!
!
suspend fun <V> await(f: CompletableFuture<V>, c: Continuation<V>) {!
f.whenComplete { value, throwable ->!
if (throwable == null)!
c.resume(value)!
else!
c.resumeWithException(throwable)!
}!
}!
!
async()	
  
fun moreWork() = async {!
println("Work started")!
val str = await(work())!
println("Work completed: $str")!
}!
!
fun <T> async(!
coroutine c: FutureController<T>.() -> Continuation<Unit>!
): CompletableFuture<T> {!
val controller = FutureController<T>()!
c(controller).resume(Unit)!
return controller.future!
}!
implicit	
  receiver	
   λ	
  has	
  no	
  params	
  
Controller	
  
@AllowSuspendExtensions!
class FutureController<T> {!
internal val future = CompletableFuture<T>()!
!
suspend fun <V> await(f: CompletableFuture<V>, c: Continuation<V>) {!
f.whenComplete { value, throwable ->!
if (throwable == null)!
c.resume(value)!
else!
c.resumeWithException(throwable)!
}!
}!
!
operator fun handleResult(value: T, c: Continuation<Nothing>) {!
future.complete(value)!
}!
!
operator fun handleException(t: Throwable, c: Continuation<Nothing>) {!
future.completeExceptionally(t)!
}!
}!
fun work() = async {!
Thread.sleep(200)!
"done"!
}!
Extensibility	
  
suspend fun <V> FutureController<*>.await(!
lf: ListenableFuture<V>, c: Continuation<V>!
) {!
Futures.addCallback(lf, object : FutureCallback<V> { !
override fun onSuccess(value: V) {!
c.resume(value)!
}!
override fun onFailure(e: Throwable) {!
c.resumeWithException(throwable)!
}!
})!
}!
!
// Example!
async {!
val res1 = await(getCompletableFuture()) !
val res2 = await(getListeableFuture())!
}!
Summary:	
  Corou%ne	
  Libraries	
  
•  fun	
  async(coroutine	
  c:	
  …)	
  
–  func%on	
  with	
  a	
  coroutine parameter	
  
	
  
•  suspend	
  fun	
  await(…,	
  c:	
  Continuation<…>)	
  
–  func%on	
  marked	
  suspend !
–  con%nua%on	
  is	
  implicitly	
  passed	
  in	
  at	
  the	
  call	
  site	
  
	
  
•  class	
  Controller	
  
–  declares	
  suspend func%ons	
  
•  may	
  allow	
  suspend extensions	
  
–  declares	
  return/excep%on	
  handlers	
  
How	
  Suspension	
  Works	
  
fun moreWork() = async {!
println("Work started")!
val str = await(work())!
println("Work completed: $str")!
}!
!
!
!
!
!
!
!
!
!
.!
controller.await(!
work(), !
current_continuation!
)!
return!
Yield	
  (The	
  C#	
  Way)	
  
IEnumerable<int>	
  Fibonacci()	
  {	
  
	
  	
  	
  	
  var	
  cur	
  =	
  1;	
  
	
  	
  	
  	
  var	
  next	
  =	
  1;	
  
	
  
	
  	
  	
  	
  yield	
  return	
  1;	
  
	
  
	
  	
  	
  	
  while	
  (true)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  yield	
  return	
  next;	
  
	
  
	
  	
  	
  	
  	
  	
  	
  	
  var	
  tmp	
  =	
  cur	
  +	
  next;	
  
	
  	
  	
  	
  	
  	
  	
  	
  cur	
  =	
  next;	
  
	
  	
  	
  	
  	
  	
  	
  	
  next	
  =	
  tmp;	
  
	
  	
  	
  	
  }	
  
}	
  
Infinite	
  (lazy)	
  sequence	
  of	
  	
  
Fibonacci	
  numbers	
  
Example:	
  Lazy	
  Fibonacci	
  
val fibonacci: Sequence<Int> = generate {!
var cur = 1!
var next = 1!
!
yield(1)!
!
while (true) {!
yield(next)!
!
val tmp = cur + next!
cur = next!
next = tmp!
}!
}!
!
assertEquals("1, 1, 2, 3, 5", fibonacci.take(5).joinToString())	
  
fun <T> generate(!
coroutine c: GeneratorController<T>.() -> Continuation<Unit>!
): Sequence<T> =!
object : Sequence<T> {!
override fun iterator(): Iterator<T> {!
val iterator = GeneratorController<T>()!
iterator.setNextStep(c(iterator))!
return iterator!
}!
}!
!
class GeneratorController<T> : AbstractIterator<T>() {!
...!
suspend fun yield(value: T, c: Continuation<Unit>) {!
setNext(value)!
setNextStep(c)!
}!
...!
}	
  
Compiling	
  to	
  State	
  Machines	
  
generate {!
var cur = 1!
var next = 1!
!
yield(1)!
!
while (true) {!
yield(next)!
!
val tmp = cur + next!
cur = next!
next = tmp!
}!
}	
  
L0	
  
L1	
  
L2	
  
var cur = 1!
var next = 1	
  
true	
  
val tmp = cur + next!
cur = next!
next = tmp!
val fibonacci = generate {!
var cur = 1!
var next = 1!
!
yield(1)!
!
while (true) {!
yield(next)!
!
val tmp = cur + next!
cur = next!
next = tmp!
}!
}	
  
Compiling	
  Corou%nes	
  (I)	
  
class fibonacci$1 implements Function1, !
Continuation {!
	
  
	
  	
  	
  	
  volatile	
  GeneratorController	
  controller	
  
	
  	
  	
  	
  volatile	
  int	
  label	
  =	
  -­‐2	
  
	
  
	
  	
  	
  	
  volatile	
  int	
  cur	
  
	
  	
  	
  	
  volatile	
  int	
  next	
  
	
  
	
  
	
  	
  	
  	
  public	
  Continuation<Unit>	
  invoke(	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  GeneratorController	
  controller)	
  
	
  
	
  	
  	
  	
  public	
  void	
  resume(Object	
  param)	
  
	
  	
  	
  	
  public	
  void	
  resumeWithException(Throwable	
  e)	
  
	
  	
  	
  	
  private	
  void	
  doResume(Object	
  param,	
  Throwable	
  e)	
   	
  	
  
}	
  
for	
  shared	
  local	
  variables	
  
Compiling	
  Corou%nes	
  (II)	
  
•  Fields:	
  
–  GeneratorController	
  controller	
  
–  int	
  label	
  
	
  
	
  
•  void	
  doResume(Object	
  param,	
  Throwable	
  e)	
  
–  tableswitch	
  (label)	
  
  case	
  0:	
  L0	
  
  case	
  1:	
  L1	
  
  case	
  2:	
  L2	
  
–  L0:	
  
  ...	
  
  label	
  =	
  1	
  
  controller.yield(1,	
  /*	
  continuation	
  =	
  */	
  this)	
  
  return	
  
–  L1:	
  
  ...	
  
  label	
  =	
  2	
  
  controller.yield(next,	
  /*	
  continuation	
  =	
  */	
  this)	
  
  return	
  
–  L2:	
  
  ...	
  
L0	
  
L1	
  
L2	
  
var cur = 1!
var next = 1	
  
true	
  
val tmp = cur + next!
cur = next!
next = tmp!
Compiling	
  Corou%nes	
  (III)	
  
–  L0:	
  
  var	
  cur	
  =	
  1	
  
  var	
  next	
  =	
  1	
  
  this.cur	
  =	
  cur	
  
  this.next	
  =	
  next	
  
  this.label	
  =	
  1	
  
  this.controller.yield(1,	
  this)	
  
  return	
  
L0	
  
L1	
  
L2	
  
var cur = 1!
var next = 1	
  
Compiling	
  Corou%nes	
  (IV)	
  
•  void	
  doResume(Object	
  param,	
  Throwable	
  e)	
  
–  L1:	
  
  cur	
  =	
  this.cur	
  
  next	
  =	
  this.next	
  
  if	
  (e	
  !=	
  null)	
  throw	
  e	
  
  //	
  while	
  (true)	
  {	
  
  this.cur	
  =	
  cur	
  
  this.next	
  =	
  next	
  
  this.label	
  =	
  2	
  
  this.controller.yield(next,	
  this)	
  
  return	
  
L0	
  
L1	
  
L2	
  
true	
  
Summary:	
  Compiling	
  Corou%nes	
  
•  Note:	
  generate()/yield()	
  can	
  be	
  expressed	
  	
  
–  flexibility:	
  þ
•  Corou%ne	
  body	
  is	
  compiled	
  to	
  a	
  state	
  machine	
  
•  Only	
  one	
  instance	
  is	
  allocated	
  at	
  run%me	
  
asyncUI	
  {	
  	
  
val	
  image	
  =	
  await(loadImage(url))	
  
myUI.setImage(image)	
  
}	
  
IOExcep%on	
  
CannotAwaitExcep%on	
  
WindowDisposedExcep%on	
  
Excep%on	
  Handling	
  
Throwing	
  and	
  Catching	
  
•  Who	
  can	
  throw	
  
–  Synchronous	
  code	
  (inside	
  a	
  corou%ne)	
  
–  Asynchronous	
  opera%ons	
  (called	
  from	
  corou%ne)	
  
–  Library	
  code	
  (that	
  manages	
  the	
  corouitne)	
  
•  Who	
  can	
  catch	
  
–  The	
  corou%ne	
  itself	
  (user	
  code)	
  
–  Library	
  code	
  
Controller.handleExcep%on(e)	
  
void	
  doResume(Object	
  param,	
  Throwable	
  e)	
  
	
  
tableswitch	
  (label)	
  
case	
  0:	
  L0	
  
case	
  1:	
  L1	
  
case	
  2:	
  L2	
  
try	
  {	
  
  L0:	
  
  ...	
  
  label	
  =	
  1	
  
  controller.await(...,	
  /*	
  continuation	
  =	
  */	
  this)	
  
  return	
  
  L1:	
  
  ...	
  
  label	
  =	
  2	
  
  controller.await(...,	
  /*	
  continuation	
  =	
  */	
  this)	
  
  return	
  
  L2:	
  
  ...	
  
  }	
  catch	
  (Throwable	
  e)	
  {	
  
  controller.handleException(e)	
  
  }	
  
Rou%ng	
  Asynchronous	
  Excep%ons	
  
•  void	
  doResume(Object	
  param,	
  Throwable	
  e)	
  
	
  	
  	
  ...	
  
–  L1:	
  
  //	
  fields	
  -­‐>	
  locals	
  
  if	
  (e	
  !=	
  null)	
  throw	
  e	
  
  ...	
  
  //	
  locals	
  -­‐>	
  fields	
  
  this.label	
  =	
  2	
  
  this.controller.yield(next,	
  this)	
  
  return	
  
suspend fun await(f, c) {!
f.whenComplete { value, e ->!
if (throwable == null)!
c.resume(value)!
else!
c.resumeWithException(e)	
  
Example:	
  Excep%on	
  Handling	
  
asyncUI	
  {	
  
	
  	
  	
  	
  val	
  image	
  =	
  try	
  {	
  
	
  	
  	
  	
  	
  	
  	
  await(	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  loadImage(url)	
  
	
  	
  	
  	
  	
  	
  	
  )	
  
	
  	
  	
  	
  }	
  catch(e:	
  Exception)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  log(e)	
  
	
  	
  	
  	
  	
  	
  	
  	
  throw	
  e	
  
	
  	
  	
  	
  }	
  
	
  
	
  	
  	
  	
  myUI.setImage(image)	
  
}	
  
Operation	
  order:	
  
•  loadImage(url)	
  
•  -­‐>	
  tmp_future	
  
•  -­‐>	
  actual_work()	
  
•  await(tmp_future)	
  
•  <suspend>	
  
•  actual_work()	
  completes	
  
•  <resume>	
  
•  myUI.setImage(image)	
  
actual_work(url)	
  
worker	
  	
  
thread	
  
Summary:	
  Excep%on	
  Handling	
  
•  Uniform	
  treatment	
  of	
  all	
  excep%ons	
  
–  both	
  sync	
  and	
  async	
  
•  Default	
  handler:	
  controller.handleException(e)	
  
•  Not	
  covered	
  in	
  this	
  talk	
  
–  Suspending	
  in	
  finally	
  blocks	
  
–  Calling	
  finally	
  blocks	
  through	
  Continuation<T>	
  
Appendix.	
  Serializable	
  Corou%nes?	
  
serializableAsync(getDB())	
  {	
  
	
  	
  	
  	
  val	
  newUser	
  =	
  showRegistrationForm()	
  
	
  	
  	
  	
  sendConfirmationEmail(newUser)	
  
	
  	
  	
  	
  if	
  (awaitEmailAddressConfirmation(newUser))	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  registration	
  confirmed	
  in	
  time	
  
	
  	
  	
  	
  	
  	
  	
  	
  confirmRegistration(getDB(),	
  newUser)	
  
	
  	
  	
  	
  	
  	
  	
  	
  showWelcomeScreen(newUser)	
  
	
  	
  	
  	
  }	
  else	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  //	
  registration	
  not	
  confirmed	
  
	
  	
  	
  	
  	
  	
  	
  	
  cancelRegistration(getDB(),	
  newUser)	
  
	
  	
  	
  	
  }	
  
}	
  
Suspending	
  	
  
Calls	
  
Data	
  to	
  be	
  serialized:	
  
•  label	
  (state	
  of	
  the	
  SM)	
  
•  newUser	
  

More Related Content

What's hot

RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture AppDynamics
 
Docker advance topic
Docker advance topicDocker advance topic
Docker advance topicKalkey
 
An intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECSAn intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECSYevgeniy Brikman
 
LevelDB 간단한 소개
LevelDB 간단한 소개LevelDB 간단한 소개
LevelDB 간단한 소개종빈 오
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootOmri Spector
 
쿠버네티스의 이해 #1
쿠버네티스의 이해 #1쿠버네티스의 이해 #1
쿠버네티스의 이해 #1상욱 송
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?Simplilearn
 
Kubernetes #1 intro
Kubernetes #1   introKubernetes #1   intro
Kubernetes #1 introTerry Cho
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXLRob Gietema
 
Firebase - Dynamic Links
Firebase - Dynamic LinksFirebase - Dynamic Links
Firebase - Dynamic LinksFilipe Nunes
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
Intro To React Native
Intro To React NativeIntro To React Native
Intro To React NativeFITC
 

What's hot (20)

RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
Docker advance topic
Docker advance topicDocker advance topic
Docker advance topic
 
Node.js 기본
Node.js 기본Node.js 기본
Node.js 기본
 
An intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECSAn intro to Docker, Terraform, and Amazon ECS
An intro to Docker, Terraform, and Amazon ECS
 
LevelDB 간단한 소개
LevelDB 간단한 소개LevelDB 간단한 소개
LevelDB 간단한 소개
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring Boot
 
Express node js
Express node jsExpress node js
Express node js
 
쿠버네티스의 이해 #1
쿠버네티스의 이해 #1쿠버네티스의 이해 #1
쿠버네티스의 이해 #1
 
Express JS
Express JSExpress JS
Express JS
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
Rest assured
Rest assuredRest assured
Rest assured
 
Kubernetes #1 intro
Kubernetes #1   introKubernetes #1   intro
Kubernetes #1 intro
 
React Router: React Meetup XXL
React Router: React Meetup XXLReact Router: React Meetup XXL
React Router: React Meetup XXL
 
Firebase - Dynamic Links
Firebase - Dynamic LinksFirebase - Dynamic Links
Firebase - Dynamic Links
 
Postman
PostmanPostman
Postman
 
NodeJS
NodeJSNodeJS
NodeJS
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Intro To React Native
Intro To React NativeIntro To React Native
Intro To React Native
 

Similar to JVMLS 2016. Coroutines in Kotlin

Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrencyjgrahamc
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel ZikmundKarel Zikmund
 
InterConnect: Server Side Swift for Java Developers
InterConnect:  Server Side Swift for Java DevelopersInterConnect:  Server Side Swift for Java Developers
InterConnect: Server Side Swift for Java DevelopersChris Bailey
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go ConcurrencyCloudflare
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsLeonardo Borges
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewDmytro Zaitsev
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.UA Mobile
 
Kotlin Coroutines Reloaded
Kotlin Coroutines ReloadedKotlin Coroutines Reloaded
Kotlin Coroutines ReloadedRoman Elizarov
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to GoCloudflare
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05cKaz Yoshikawa
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?Adam Dudczak
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Go Containers
Go ContainersGo Containers
Go Containersjgrahamc
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library designLeonardo Borges
 

Similar to JVMLS 2016. Coroutines in Kotlin (20)

Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 
InterConnect: Server Side Swift for Java Developers
InterConnect:  Server Side Swift for Java DevelopersInterConnect:  Server Side Swift for Java Developers
InterConnect: Server Side Swift for Java Developers
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Coroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth reviewCoroutines in Kotlin. In-depth review
Coroutines in Kotlin. In-depth review
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
Kotlin Coroutines Reloaded
Kotlin Coroutines ReloadedKotlin Coroutines Reloaded
Kotlin Coroutines Reloaded
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
 
Idioms in swift 2016 05c
Idioms in swift 2016 05cIdioms in swift 2016 05c
Idioms in swift 2016 05c
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Go Containers
Go ContainersGo Containers
Go Containers
 
Go Containers
Go ContainersGo Containers
Go Containers
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
 
Music as data
Music as dataMusic as data
Music as data
 

More from Andrey Breslav

2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdfAndrey Breslav
 
Shoulders of giants: Languages Kotlin learned from
Shoulders of giants: Languages Kotlin learned fromShoulders of giants: Languages Kotlin learned from
Shoulders of giants: Languages Kotlin learned fromAndrey Breslav
 
Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Andrey Breslav
 
Flexible Types in Kotlin - JVMLS 2015
Flexible Types in Kotlin - JVMLS 2015Flexible Types in Kotlin - JVMLS 2015
Flexible Types in Kotlin - JVMLS 2015Andrey Breslav
 
Introduction to Kotlin: Brief and clear
Introduction to Kotlin: Brief and clearIntroduction to Kotlin: Brief and clear
Introduction to Kotlin: Brief and clearAndrey Breslav
 
Kotlin for Android: Brief and Clear
Kotlin for Android: Brief and ClearKotlin for Android: Brief and Clear
Kotlin for Android: Brief and ClearAndrey Breslav
 
Kotlin (Introduction for students)
Kotlin (Introduction for students)Kotlin (Introduction for students)
Kotlin (Introduction for students)Andrey Breslav
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designAndrey Breslav
 
Kotlin gets Reflection
Kotlin gets ReflectionKotlin gets Reflection
Kotlin gets ReflectionAndrey Breslav
 
Language Design Trade-offs
Language Design Trade-offsLanguage Design Trade-offs
Language Design Trade-offsAndrey Breslav
 
Kotlin: Incompetence * Motivation = Innovation?
Kotlin: Incompetence * Motivation = Innovation?Kotlin: Incompetence * Motivation = Innovation?
Kotlin: Incompetence * Motivation = Innovation?Andrey Breslav
 
Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Andrey Breslav
 
JavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
JavaOne2012: Kotlin: Practical Aspects of JVM Language ImplementationJavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
JavaOne2012: Kotlin: Practical Aspects of JVM Language ImplementationAndrey Breslav
 
[JVMLS 12] Kotlin / Java Interop
[JVMLS 12] Kotlin / Java Interop[JVMLS 12] Kotlin / Java Interop
[JVMLS 12] Kotlin / Java InteropAndrey Breslav
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Andrey Breslav
 
Kotlin @ CSClub & Yandex
Kotlin @ CSClub & YandexKotlin @ CSClub & Yandex
Kotlin @ CSClub & YandexAndrey Breslav
 
Kotlin @ StrangeLoop 2011
Kotlin @ StrangeLoop 2011Kotlin @ StrangeLoop 2011
Kotlin @ StrangeLoop 2011Andrey Breslav
 

More from Andrey Breslav (20)

2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
 
Shoulders of giants: Languages Kotlin learned from
Shoulders of giants: Languages Kotlin learned fromShoulders of giants: Languages Kotlin learned from
Shoulders of giants: Languages Kotlin learned from
 
Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?
 
Flexible Types in Kotlin - JVMLS 2015
Flexible Types in Kotlin - JVMLS 2015Flexible Types in Kotlin - JVMLS 2015
Flexible Types in Kotlin - JVMLS 2015
 
Eval4j @ JVMLS 2014
Eval4j @ JVMLS 2014Eval4j @ JVMLS 2014
Eval4j @ JVMLS 2014
 
Introduction to Kotlin: Brief and clear
Introduction to Kotlin: Brief and clearIntroduction to Kotlin: Brief and clear
Introduction to Kotlin: Brief and clear
 
Kotlin for Android: Brief and Clear
Kotlin for Android: Brief and ClearKotlin for Android: Brief and Clear
Kotlin for Android: Brief and Clear
 
Kotlin (Introduction for students)
Kotlin (Introduction for students)Kotlin (Introduction for students)
Kotlin (Introduction for students)
 
Kotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language designKotlin: Challenges in JVM language design
Kotlin: Challenges in JVM language design
 
Kotlin gets Reflection
Kotlin gets ReflectionKotlin gets Reflection
Kotlin gets Reflection
 
Language Design Trade-offs
Language Design Trade-offsLanguage Design Trade-offs
Language Design Trade-offs
 
Functions and data
Functions and dataFunctions and data
Functions and data
 
Kotlin: Incompetence * Motivation = Innovation?
Kotlin: Incompetence * Motivation = Innovation?Kotlin: Incompetence * Motivation = Innovation?
Kotlin: Incompetence * Motivation = Innovation?
 
Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?
 
JavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
JavaOne2012: Kotlin: Practical Aspects of JVM Language ImplementationJavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
JavaOne2012: Kotlin: Practical Aspects of JVM Language Implementation
 
[JVMLS 12] Kotlin / Java Interop
[JVMLS 12] Kotlin / Java Interop[JVMLS 12] Kotlin / Java Interop
[JVMLS 12] Kotlin / Java Interop
 
Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011Kotlin @ Devoxx 2011
Kotlin @ Devoxx 2011
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
Kotlin @ CSClub & Yandex
Kotlin @ CSClub & YandexKotlin @ CSClub & Yandex
Kotlin @ CSClub & Yandex
 
Kotlin @ StrangeLoop 2011
Kotlin @ StrangeLoop 2011Kotlin @ StrangeLoop 2011
Kotlin @ StrangeLoop 2011
 

Recently uploaded

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 

Recently uploaded (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 

JVMLS 2016. Coroutines in Kotlin

  • 1. Corou%nes  in  Kotlin   Andrey.Breslav@JetBrains.com  
  • 2. This  talk  could  have  been  named…   •  async/await/yield   •  fibers   •  [stackless]  con%nua%ons   Suspendable   Computa%ons  
  • 3. Outline   •  Mo%va%on/Examples   •  Solu%ons  in  other  languages   •  Kotlin’s  Solu%on   –  Client  code   –  Library  code   •  Compiling  Corou%nes   •  Excep%on  Handling   •  Appendix.  Serializable  Corou%nes?  
  • 4. “Legal”   •  All  I’m  saying  is  no  more  final  than  Valhalla  J  
  • 5.   val  image  =  loadImage(url)   myUI.setImage(image)     Mo%va%on   Time-­‐consuming   opera%on   UI  Thread  
  • 6. Latency!   •  Blocking  bad.  Very  bad.  
  • 7. asyncUI  {   val  image  =  await(loadImage(url))   myUI.setImage(image)   }   Suspendable  Computa%on   Suspending   call   Con%nua%on   Time-­‐consuming   opera%on   await(…)   loadImage(url)   UI  Thread   Worker  Thread   setImage(…)  
  • 9. Combining  Futures   •  CompletableFuture     .supplyAsync  {  loadImage(url)  }     .thenAccept(myUI::setImage)   •  so  veeery  func%onal  J  
  • 10. asyncUI  {   val  image  =  loadImageAsync(url)   myUI.setImage(image)   }   Flexibility   Asynchronous   opera%on   Con%nua%on   interface  Continuation<P>  {          fun  resume(data:  P)          fun  resumeWithException(e:  Throwable)   }   <Image>   Library  Func%on   (corou%ne  builder)  
  • 11. asyncUI  {   val  image  =  await(loadImage(url))   myUI.setImage(image)   }   Run%me  Support   Con%nua%on   interface  Continuation<P>  {          fun  resume(data:  P)          fun  resumeWithException(e:  Throwable)   }   <Image>  
  • 12. Summary:  Goals   •  Asynchronous  programing  (and  more)   –  without  explicit  callbacks   –  without  explicit  Future  combinators   •  Maximum  flexibility  for  library  designers   –  with  minimal  run%me  support   –  and  no  macros  J  
  • 13. Flavors  of  Corou%nes   Stackless   Stackful   Language  restric;ons   Use  in  special  contexts  L   Use  anywhere  J   Implemented  in   C#,  Scala,  Kotlin,  …   Quasar,  Javaflow,  …   Code  transforma;on   Local  (compiler  magic)  J   All  over  the  place  L   Run;me  support   Lidle  J   Substan%al  L  
  • 14. The  C#  Way   async  Task<String>  work()  {   Thread.sleep(200);   return  “done”;   }     async  Task  moreWork()  {   Console.WriteLine(“Work  started”);   var  str  =  await  work();   Console.WriteLine($“Work  completed:  {str}”);   }  
  • 15. Example:  async/await  (I)   fun work(): CompletableFuture<String> = async {! Thread.sleep(200)! "done"! }! ! fun moreWork() = async {! println("Work started")! val str = await(work())! println("Work completed: $str")! }   type  is  op%onal  
  • 16. Example:  async/await  (I)   fun work() = async {! Thread.sleep(200)! "done"! }! ! fun moreWork() = async {! println("Work started")! val str = await(work())! println("Work completed: $str")! }  
  • 17. await()   fun moreWork() = async {! println("Work started")! val str = await(work())! println("Work completed: $str")! }! ! suspend fun <V> await(f: CompletableFuture<V>, c: Continuation<V>) {! f.whenComplete { value, throwable ->! if (throwable == null)! c.resume(value)! else! c.resumeWithException(throwable)! }! }! !
  • 18. async()   fun moreWork() = async {! println("Work started")! val str = await(work())! println("Work completed: $str")! }! ! fun <T> async(! coroutine c: FutureController<T>.() -> Continuation<Unit>! ): CompletableFuture<T> {! val controller = FutureController<T>()! c(controller).resume(Unit)! return controller.future! }! implicit  receiver   λ  has  no  params  
  • 19. Controller   @AllowSuspendExtensions! class FutureController<T> {! internal val future = CompletableFuture<T>()! ! suspend fun <V> await(f: CompletableFuture<V>, c: Continuation<V>) {! f.whenComplete { value, throwable ->! if (throwable == null)! c.resume(value)! else! c.resumeWithException(throwable)! }! }! ! operator fun handleResult(value: T, c: Continuation<Nothing>) {! future.complete(value)! }! ! operator fun handleException(t: Throwable, c: Continuation<Nothing>) {! future.completeExceptionally(t)! }! }! fun work() = async {! Thread.sleep(200)! "done"! }!
  • 20. Extensibility   suspend fun <V> FutureController<*>.await(! lf: ListenableFuture<V>, c: Continuation<V>! ) {! Futures.addCallback(lf, object : FutureCallback<V> { ! override fun onSuccess(value: V) {! c.resume(value)! }! override fun onFailure(e: Throwable) {! c.resumeWithException(throwable)! }! })! }! ! // Example! async {! val res1 = await(getCompletableFuture()) ! val res2 = await(getListeableFuture())! }!
  • 21. Summary:  Corou%ne  Libraries   •  fun  async(coroutine  c:  …)   –  func%on  with  a  coroutine parameter     •  suspend  fun  await(…,  c:  Continuation<…>)   –  func%on  marked  suspend ! –  con%nua%on  is  implicitly  passed  in  at  the  call  site     •  class  Controller   –  declares  suspend func%ons   •  may  allow  suspend extensions   –  declares  return/excep%on  handlers  
  • 22. How  Suspension  Works   fun moreWork() = async {! println("Work started")! val str = await(work())! println("Work completed: $str")! }! ! ! ! ! ! ! ! ! ! .! controller.await(! work(), ! current_continuation! )! return!
  • 23. Yield  (The  C#  Way)   IEnumerable<int>  Fibonacci()  {          var  cur  =  1;          var  next  =  1;            yield  return  1;            while  (true)  {                  yield  return  next;                    var  tmp  =  cur  +  next;                  cur  =  next;                  next  =  tmp;          }   }   Infinite  (lazy)  sequence  of     Fibonacci  numbers  
  • 24. Example:  Lazy  Fibonacci   val fibonacci: Sequence<Int> = generate {! var cur = 1! var next = 1! ! yield(1)! ! while (true) {! yield(next)! ! val tmp = cur + next! cur = next! next = tmp! }! }! ! assertEquals("1, 1, 2, 3, 5", fibonacci.take(5).joinToString())  
  • 25. fun <T> generate(! coroutine c: GeneratorController<T>.() -> Continuation<Unit>! ): Sequence<T> =! object : Sequence<T> {! override fun iterator(): Iterator<T> {! val iterator = GeneratorController<T>()! iterator.setNextStep(c(iterator))! return iterator! }! }! ! class GeneratorController<T> : AbstractIterator<T>() {! ...! suspend fun yield(value: T, c: Continuation<Unit>) {! setNext(value)! setNextStep(c)! }! ...! }  
  • 26. Compiling  to  State  Machines   generate {! var cur = 1! var next = 1! ! yield(1)! ! while (true) {! yield(next)! ! val tmp = cur + next! cur = next! next = tmp! }! }   L0   L1   L2   var cur = 1! var next = 1   true   val tmp = cur + next! cur = next! next = tmp!
  • 27. val fibonacci = generate {! var cur = 1! var next = 1! ! yield(1)! ! while (true) {! yield(next)! ! val tmp = cur + next! cur = next! next = tmp! }! }   Compiling  Corou%nes  (I)   class fibonacci$1 implements Function1, ! Continuation {!          volatile  GeneratorController  controller          volatile  int  label  =  -­‐2            volatile  int  cur          volatile  int  next              public  Continuation<Unit>  invoke(                                                GeneratorController  controller)            public  void  resume(Object  param)          public  void  resumeWithException(Throwable  e)          private  void  doResume(Object  param,  Throwable  e)       }   for  shared  local  variables  
  • 28. Compiling  Corou%nes  (II)   •  Fields:   –  GeneratorController  controller   –  int  label       •  void  doResume(Object  param,  Throwable  e)   –  tableswitch  (label)     case  0:  L0     case  1:  L1     case  2:  L2   –  L0:     ...     label  =  1     controller.yield(1,  /*  continuation  =  */  this)     return   –  L1:     ...     label  =  2     controller.yield(next,  /*  continuation  =  */  this)     return   –  L2:     ...   L0   L1   L2   var cur = 1! var next = 1   true   val tmp = cur + next! cur = next! next = tmp!
  • 29. Compiling  Corou%nes  (III)   –  L0:     var  cur  =  1     var  next  =  1     this.cur  =  cur     this.next  =  next     this.label  =  1     this.controller.yield(1,  this)     return   L0   L1   L2   var cur = 1! var next = 1  
  • 30. Compiling  Corou%nes  (IV)   •  void  doResume(Object  param,  Throwable  e)   –  L1:     cur  =  this.cur     next  =  this.next     if  (e  !=  null)  throw  e     //  while  (true)  {     this.cur  =  cur     this.next  =  next     this.label  =  2     this.controller.yield(next,  this)     return   L0   L1   L2   true  
  • 31. Summary:  Compiling  Corou%nes   •  Note:  generate()/yield()  can  be  expressed     –  flexibility:  þ •  Corou%ne  body  is  compiled  to  a  state  machine   •  Only  one  instance  is  allocated  at  run%me  
  • 32. asyncUI  {     val  image  =  await(loadImage(url))   myUI.setImage(image)   }   IOExcep%on   CannotAwaitExcep%on   WindowDisposedExcep%on   Excep%on  Handling  
  • 33. Throwing  and  Catching   •  Who  can  throw   –  Synchronous  code  (inside  a  corou%ne)   –  Asynchronous  opera%ons  (called  from  corou%ne)   –  Library  code  (that  manages  the  corouitne)   •  Who  can  catch   –  The  corou%ne  itself  (user  code)   –  Library  code  
  • 34. Controller.handleExcep%on(e)   void  doResume(Object  param,  Throwable  e)     tableswitch  (label)   case  0:  L0   case  1:  L1   case  2:  L2   try  {     L0:     ...     label  =  1     controller.await(...,  /*  continuation  =  */  this)     return     L1:     ...     label  =  2     controller.await(...,  /*  continuation  =  */  this)     return     L2:     ...     }  catch  (Throwable  e)  {     controller.handleException(e)     }  
  • 35. Rou%ng  Asynchronous  Excep%ons   •  void  doResume(Object  param,  Throwable  e)        ...   –  L1:     //  fields  -­‐>  locals     if  (e  !=  null)  throw  e     ...     //  locals  -­‐>  fields     this.label  =  2     this.controller.yield(next,  this)     return   suspend fun await(f, c) {! f.whenComplete { value, e ->! if (throwable == null)! c.resume(value)! else! c.resumeWithException(e)  
  • 36. Example:  Excep%on  Handling   asyncUI  {          val  image  =  try  {                await(                        loadImage(url)                )          }  catch(e:  Exception)  {                  log(e)                  throw  e          }            myUI.setImage(image)   }   Operation  order:   •  loadImage(url)   •  -­‐>  tmp_future   •  -­‐>  actual_work()   •  await(tmp_future)   •  <suspend>   •  actual_work()  completes   •  <resume>   •  myUI.setImage(image)   actual_work(url)   worker     thread  
  • 37. Summary:  Excep%on  Handling   •  Uniform  treatment  of  all  excep%ons   –  both  sync  and  async   •  Default  handler:  controller.handleException(e)   •  Not  covered  in  this  talk   –  Suspending  in  finally  blocks   –  Calling  finally  blocks  through  Continuation<T>  
  • 38. Appendix.  Serializable  Corou%nes?   serializableAsync(getDB())  {          val  newUser  =  showRegistrationForm()          sendConfirmationEmail(newUser)          if  (awaitEmailAddressConfirmation(newUser))  {                  //  registration  confirmed  in  time                  confirmRegistration(getDB(),  newUser)                  showWelcomeScreen(newUser)          }  else  {                  //  registration  not  confirmed                  cancelRegistration(getDB(),  newUser)          }   }   Suspending     Calls   Data  to  be  serialized:   •  label  (state  of  the  SM)   •  newUser  

Editor's Notes

  1. A rarity: Language design talk As Brian and Dan mention every time in the last few years, we started as “here’s my language, look how cool it is”, and now JVMLS means more a summit of people who speak the JVM language 
  2. A car blocking others Blocking one’s driveway
  3. It helps, but async/await is so much more straightforward