1

I have a for loop that consists of looping towards infinity and inside that for loop, there is a Thread.sleep(T)function, the sleeping time varies from 50ms to 1s. I know there are performance and user experience costs for using a sleep function inside a loop.

So what are the Kotlin alternatives ? (I found answers but all of them are in Java, I wanna know the best alternatives in Kotlin)

2
  • 2
    It depends on the reason you would be sleeping in the first place. Thread.sleep blocks the thread its running on, which might be what you want. If you're on a UI/input processing thread, then it's almost certainly not what you want because it locks up the interface. Kotlin provides coroutines as an easy way to add delays to code execution without blocking a thread, but it's a huge topic to cover in an answer here. Commented Jan 24, 2021 at 22:33
  • It is strictly related to UI-updating methods, so for sure I don't want any thread to be blocked. The coroutines do just the job. Thank you for pointing out that Thread.sleep is still functional. Commented Jan 24, 2021 at 23:19

1 Answer 1

2

Use Kotlin Coroutines there is delay(millis:Long) function that is cheaper than Thread.sleep()

 import kotlinx.coroutines.* fun main() { GlobalScope.launch { // launch a new coroutine in background and continue delay(1000L) // non-blocking delay for 1 second (default time unit is ms) println("World!") // print after delay } println("Hello,") // main thread continues while coroutine is delayed Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive } 
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please explain why it is "cheaper than Thread.sleep()"?
Thread.sleep() suspends the thread itself whereas delay() suspends the coroutine not the thread. In one thread there may be several coroutines. Another example if you open 1 million thread and do simple adding operation you get exception OutOfMemoryError but if you open 1 mlillion Coroutines you get the result without exception. So Coroutine is lightweight and "cheaper" than Thread in terms of memory and resources. I tried to explain sorry if u use wrong words, English is my second language :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.