Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the delay function in Kotlin internally work?

I have been trying to understand how Kotlin coroutines work and I came across the delay function.

My understanding of this works is,

  • delay suspends the current thread, where the thread, unlike sleep, does not consume CPU cycles and is freed to execute other tasks.
  • How this works is that the code after the delay function is captured as a lambda(Continuation) and can be executed after the given time period by a different thread.
  • The implementation seems similar to Javascript's execution model, where the delay function causes the continuation to be stored on some kind of a task queue and releases the current thread. After the specified time is elapsed, this task is scheduled on an available thread.

Is my understanding correct? Also, is there a relation between the thread that calls delay and the thread that executes the code following the call to delay.

Thanks!

like image 209
abhijeetpawar Avatar asked Jul 06 '18 16:07

abhijeetpawar


People also ask

How does delay work Kotlin?

delay is a special suspending function. It suspends the coroutine for a specific time. Suspending a coroutine does not block the underlying thread, but allows other coroutines to run and use the underlying thread for their code.

How do you implement delay in Kotlin?

There is no direct way to achieve this in Kotlin, but we can use Java library functions in Kotlin for this purpose since Kotlin is based on Java. We will use the Timer() and schedule() functions to call a function after a delay.

What is the difference between Kotlin thread sleep () and delay ()?

The difference is that delay is a suspend function that won't block the thread, while Thread. sleep() will block the thread.


1 Answers

Yes. Your understanding is correct. The difference between JS and Kotlin is that the task queue that is used to execute the continuation can be customized by the programmer via CoroutineDispatcher. In general, there is no relation between the thread that calls delay and the thread where continuation is scheduled for resume. It is determined by two factors:

  • If the coroutine uses the Unconfined dispatcher, then the thread where the continuation is resumed is some system timer thread used internally in the implementation of delay. You can write your own version of delay that resumes Unconfined continuations on the thread of your choice.

  • If the coroutine uses some confined dispatcher, then it resumes on the thread or a pool of threads defined by that dispatcher. A number of dispatchers are provided out of the box. For example, in Android using the UI dispatcher, the coroutine is going to be always resumed on the Android UI thread. In general, in Kotlin/JVM you can take any Executor and convert it to CoroutineDispatcher using asCoroutineDispatcher extension.

like image 123
Roman Elizarov Avatar answered Nov 15 '22 09:11

Roman Elizarov