A Drive To Kotlin Coroutines
September 28, 2018
Tushar Dhole
The reality of Concurrency
Concurrency and parallelism are two related but distinct concepts.
Concurrency essentially means, that task A and task B both need to happen independently of each other, and A starts running, and then B starts before A is finished.�Ex; There are two threads A and B both having 10 statements. We ask single core processor to execute both threads concurrently.��The processor will have some strategy, where it will execute statement 1 of A, then switch to B execute statement 1. Again switch to T1 for statement 2 and so on..
This gives a feel of concurrency but in a one unit time a processor can execute only one instruction.
The reality of Concurrency
The crux is that concurrency on single core is possible at the cost of context switching.��In modern computers we have multiple cores using which OS can leverage pure parallelism as well as concurrency.
Understanding the problem
Item 1
We can not create unlimited threads or millions of threads.
Item 2
Context switching at run time by OS is heavy and time consuming.
Solution 1 - Thread Pool
Thread Pool
Using thread pool we can ensure that threads are reused and at a time only particular number of Threads can be created
This will limit the number of threads and hence system will not crash because of memory crunch
But still context switching is at OS level which is heavy and slow
Solution 2 - Coroutines
This solution is implemented in Kotlin
Overview
Coroutines are no magic, Coroutines are not thread.
Coroutines are better way of context switching at compile time.
Coroutines are lighter than thread.
Building Blocks of Coroutines
Suspended Points
A statement in code block where the execution can be paused and later resumed by the same or another thread.
Coroutine
An object which takes a code block with suspension points and manages the suspension and resumption
Key Points
Coroutines are same as thread pool if there are no suspension points in the coroutine execution block
Coroutines are more efficient than Thread Pool if there are suspension points in the coroutine execution block. As this suspension points allows to take context switching at compile time instead of OS level context switching.
Key Points
In threads, if a thread creates another thread then parent thread needs to wait or be blocked to get result from child thread.
In coroutines, if a coroutine creates another coroutine then parent coroutine thread do not require to wait or be blocked to get result from child coroutine.
Android Advantage
Coroutines elegant API makes it very simple to get the data on background thread and switch to main thread.
Tushar Dhole
Software Developer