Kotlin coroutines anatomy (TBD)

Thread

Lifecycle

How thread work under the hood

  • Share memory
  • Thread vs ThreadLocal
  • Thread memory footprint

    Thread communication

Pros & Cons

  • Mutex (atomic)
  • Asynchronous
  • Race condition
  • Dead lock
  • Visibility & mutual object

Process

Process communication

Coroutines

  • Concept exist since 1950 (1960?)
  • Also available in other language likes Go, Perl and Python

Coroutines element

  • Suspendable function
  • Coroutine builder: function that create coroutine and return Job
  • Coroutine scope: include coroutine context: control how coroutine setup, cancel coroutine and choose which thread to run coroutine
  • Coroutine context: rules for exceute coroutine
  • Job & CoroutineDispatcher make up a coroutine context
  • Job: track coroutine state, allow coroutines to be track and manually cancel early
  • CoroutineDispatcher: dispatch coroutine to desire thread, build-in dispatchers:
    • Dispatchers.Default: for general work, thread pool size = number of CPU core
    • Dispatchers.IO: for IO work, thread pool size with high number of thread
    • Dispatchers.Main: UI/main thread
    • Dispatchers.Unconfined
  • async/await
  • Deferred
  • Continuation

Coroutines builder

  • launch
  • async

    How coroutines work

Coroutines under the hood

Structured concurrency

Coroutines communication

Coroutines evolution

  • Sequential programming
  • Callback hell Off-load work with worker thread and callback
  • Rx
  • Promise, Future, Deffer, Completable

    Coroutines vs Thread

    Similar

What is the pattern of Couroutines lib

Diff
  • Thread low-level API vs Coroutines is high-level API under the hood it used thread pool
  • Each thread cost around ~2M memory footprint
  • Threads share memory in process

Same

  • Off-load work to worker thread

Pros vs Cons

  • Standalone lib

References

  1. https://speakerdeck.com/elizarov
  2. https://dzone.com/articles/how-much-memory-does-a-java-thread-take