10

I was going through the concept of co-routines and it's usage and implementation in kotlin.

I googled and read few answers as in how it is different from threads in terms of architecture and performance.

Very well explained here,

Difference between a "coroutine" and a "thread"?

Fair enough, co-routines are great, no memory overhead, great performance, no dead-locks, race-conditions and etc. and easy to use.

Now, here are few things, I am confused about and would like more clarity on the same -

  1. When should I use co-routines and thread in Android? Or should I stick with just co-routines?
  2. If, I just stick with co-routines then how it will take advantage of CPU-cores, as it runs on a single thread.

Co-routines are great to use, but how it takes advantage of multiple cores for performance.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
Ritt
  • 3,181
  • 3
  • 22
  • 51

1 Answers1

10

Threads and coroutines are almost orthogonal features.

Coroutines are about your programming model and threads are about your execution model.

If you want to fetch a URL or perform a heavyweight computation in Android, you have to use async programming. You have the choice to do it the old-fashioned way, with callbacks, or with coroutines, which make those crutches disappear. You simply call a suspendable function and get the result as its return value.

Note that for the heavyweight computation you'll use extra threads with or without coroutines. For network ops you don't need extra threads, with or without coroutines.

A great analogy is that threads are to coroutines what CPU cores are to threads:

The OS assigns a thread to a CPU core until the thread suspends. Later on, the same thread can resume on another core.

The coroutine dispatcher assigns a coroutine to a thread until the coroutine suspends. Later on, the same coroutine can resume on another thread.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • Do Kotlin coroutines automatically spawn threads when necessary (when many cores are needed)? Or just coroutine context does spawn threads? – Naetmul Apr 02 '18 at 09:31
  • 1
    A coroutine itself has nothing to do with threads. A suspended coroutine is nothing more than a plain Java object with a `resume()` method. All the thread manipulations are in the coroutine dispatcher (which is a part of the context). The `UI` dispatcher never spawns threads, it just submits the coroutine to the UI thread. `Unconfined` just resumes the coroutine on the calling thread. Even `CommonPool` doesn't spawn threads on its own, but simply submits the coroutine to a global `ExecutorService`, which will then do whatever it's configured to do. – Marko Topolnik Apr 02 '18 at 09:42