How to Sleep to Suspend a Thread's Execution in Kotlin

Kailash Vaviya Feb 02, 2024
  1. Use the Thread.sleep() Function in Kotlin
  2. Use the TimeUnit’s sleep() Function in Kotlin
  3. Use the delay() Function in Kotlin
  4. Use the ScheduledExecutorService in Kotlin
  5. Conclusion
How to Sleep to Suspend a Thread's Execution in Kotlin

Sleeping, or delaying the execution of code, is a common requirement in many programming scenarios. In Kotlin, there are several methods to achieve this.

Java has a wait() function that pauses the current thread’s execution. The thread sleeps until another thread enters and notifies the sleeping thread.

But is there an equivalent available in Kotlin? Kotlin does not have the wait() function, but it has the sleep() function.

The Kotlin sleep() function suspends the execution of a particular coroutine. While this does not pause the execution, it allows the execution of other coroutines.

In this article, we will explore different approaches to implement the sleep functionality in Kotlin, providing example codes and explanations for each method.

Use the Thread.sleep() Function in Kotlin

Thread.sleep() is a method provided by the Java Virtual Machine (JVM) for controlling the flow of execution in a multithreaded program. When a thread invokes Thread.sleep(), it temporarily relinquishes the CPU and enters a sleep state. This means the thread will not execute any further instructions for the specified duration.

The Thread.sleep() method is a straightforward way to pause the execution of a Kotlin program for a specified amount of time. It takes a single argument, which represents the duration of the sleep in milliseconds.

We can use the Thread.sleep() function to make a coroutine go to sleep and allow other independent coroutines to run. The syntax for using the sleep() function is:

Thread.sleep(milliseconds: Long)

milliseconds: The duration for which the thread will sleep, specified in milliseconds.

Here’s an example where we use the Kotlin sleep() function to suspend the execution of a coroutine by 3 seconds.

fun main() {

    println("Suspending execution")

    try {
        // making the coroutine sleep for 3 seconds
        Thread.sleep(3000)
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }

    println("Resuming execution")
}

Output:

Using Kotlin sleep function from Thread

This code demonstrates how to pause the execution of a program for a specific duration using the Thread.sleep() function. It starts by printing "Suspending execution", then uses a try-catch block to handle potential interruptions during the sleep.

The program sleeps for 3 seconds (3000 milliseconds) before printing "Resuming execution" to indicate that normal execution has resumed. This technique is useful for introducing delays in program execution, simulating time-dependent processes, or waiting for specific conditions to be met.

Use the TimeUnit’s sleep() Function in Kotlin

Like Thread.sleep(), we can also use TimeUnit to suspend the execution of a thread.

TimeUnit is an enum class in Kotlin that represents time durations at a given unit of granularity. It provides a set of constants to specify time units like seconds, milliseconds, microseconds, and nanoseconds.

The sleep() function, part of the TimeUnit class, allows us to pause the execution of a program for a specific duration, defined in terms of the chosen time unit.

The syntax for using TimeUnit’s sleep() function in Kotlin is as follows:

TimeUnit.unit.sleep(duration)

Here’s what each part of the syntax means:

  • TimeUnit: Refers to the enum class that represents time durations at a given unit of granularity.
  • unit: Specifies the time unit in which the duration is defined. This can be one of the constants provided by the TimeUnit enum class, such as SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS, etc.
  • duration: Represents the amount of time to sleep, specified in terms of the chosen time unit. It’s an integer value.

For example, to sleep for 3 seconds, you would use:

TimeUnit.SECONDS.sleep(3)

This would pause the execution of the program for 3 seconds.

While the Thread technique only accepts the number of milliseconds as input, TimeUnit accepts seven different time units. These 7 time units are:

  1. Nanoseconds
  2. Microseconds
  3. Milliseconds
  4. Seconds
  5. Minute
  6. Hours
  7. Days

The TimeUnit automatically converts the passed value into milliseconds, which the sleep() function accepts.

The TimeUnit methods are a part of the java.util.concurrent library. Hence, we need to import the concurrent library to use this method.

Here’s an example demonstrating the Kotlin sleep() function from TimeUnit.

import java.util.concurrent.TimeUnit

fun main() {
    println("Suspending execution")

    try {
        // // making the coroutine sleep for 3 seconds
        TimeUnit.SECONDS.sleep(3)
    } catch (e: InterruptedException) {
        e.printStackTrace()
    }
    println("Resuming execution")
}

Output:

Using Kotlin sleep function from TimeUnit

This code showcases the use of the TimeUnit and the sleep() functions to pause program execution for a specified duration. It imports TimeUnit for time unit constants.

In the main() function, it first prints "Suspending execution". Then, it attempts to sleep the program for 3 seconds using TimeUnit.SECONDS.sleep(3).

Next, it catches any potential InterruptedException and prints the stack trace. Finally, it prints "Resuming execution" after the sleep duration.

Use the delay() Function in Kotlin

Besides the Kotlin sleep() function, we can also use the delay() function to suspend the execution of a coroutine. The delay() function also accepts milliseconds as input.

The delay() function is a suspending function provided by Kotlin’s coroutine library. It allows you to pause the execution of a coroutine for a specified amount of time without blocking the thread.

This makes it ideal for scenarios where you want to introduce controlled delays in your code, such as waiting for a response from a server or simulating real-time events.

The syntax of the delay() function is as follows:

suspend fun delay(timeMillis: Long)

Here’s what each part of the syntax means:

  • suspend: This keyword indicates that the function can suspend the execution of a coroutine. It means that this function can only be called from within a coroutine or another suspending function.
  • fun: This is the keyword used to declare a function in Kotlin.
  • delay: This is the name of the function.
  • timeMillis: Long: This is the parameter that the function takes. It specifies the duration of the delay in milliseconds. It is of type Long, which means it can accept a long integer value.
  • Unit: This is the return type of the function. Unit is Kotlin’s equivalent of void in Java, indicating that the function does not return any value.

Here’s an example to show the usage of the Kotlin delay() function.

import kotlinx.coroutines.*

fun main() = runBlocking {
    launch { // launches a new coroutine
        delay(2000L) // This delays the execution by 2 seconds, allowing other coroutines to run independently
        println("welcome!") // This will be printed after the delay
    }
    print("Hi and ") // This will be printed first since the other coroutine is delayed
}

This code demonstrates the use of coroutines, which are lightweight threads for asynchronous programming. In the main function, the runBlocking block is used to start a coroutine and block the main thread until all the coroutines inside it are complete.

Inside the runBlocking block, a new coroutine is launched using launch. This coroutine contains two sequential operations.

First, delay(2000L) is called, which introduces a delay of 2 seconds. During this time, the coroutine pauses its execution without blocking the main thread, allowing other coroutines to run independently.

After the delay, "welcome!" is printed on the console.

Meanwhile, outside the coroutine, print("Hi and ") is executed immediately. This means "Hi and " will be printed first.

The output will look like:

Using Kotlin delay function

This example illustrates how coroutines allow for asynchronous execution of tasks, enabling concurrent operations without blocking the main thread. This is particularly useful for handling I/O operations or tasks that involve waiting, as it allows for efficient resource utilization.

Use the ScheduledExecutorService in Kotlin

The ScheduledExecutorService is part of the Java Concurrency Utilities and provides a flexible way to schedule tasks for execution. It allows you to specify when a task should run, either after a certain delay or at a fixed rate.

  • Setting Up Your Kotlin Project

    Before we dive into using ScheduledExecutorService, ensure you have a Kotlin project set up. You can create one using an IDE like IntelliJ IDEA or by using the Kotlin command-line compiler.

  • Importing Java Concurrency Utilities

    To use ScheduledExecutorService in Kotlin, you’ll need to import the necessary Java classes. Add the following imports at the beginning of your Kotlin file:

    import java.util.concurrent.Executors
    import java.util.concurrent.ScheduledExecutorService
    import java.util.concurrent.TimeUnit
    

    These imports give you access to the classes and methods needed to work with ScheduledExecutorService.

  • Creating a ScheduledExecutorService

    Next, create an instance of ScheduledExecutorService. You can do this by using the Executors.newScheduledThreadPool() method.

    This method creates a thread pool that can schedule commands to run after a given delay or to execute periodically.

    val executor: ScheduledExecutorService = Executors.newScheduledThreadPool(1)
    

    In this example, we’re creating a ScheduledExecutorService with a single thread. You can adjust the parameter to create a thread pool with a different number of threads based on your specific requirements.

  • Scheduling a Task for Delayed Execution

    To implement sleep functionality, you’ll schedule a task to run after a specified delay. This is achieved using the schedule() method of the ScheduledExecutorService.

    executor.schedule({
    	// Code to execute after the specified delay
    	println("Task executed after delay")
    }, 5, TimeUnit.SECONDS)
    

    In this example, we’re scheduling a task to execute after a delay of 5 seconds. You can adjust the delay duration by changing the second parameter (in this case, 5) and the time unit by modifying the third parameter (TimeUnit.SECONDS).

  • Shutting Down the ScheduledExecutorService

    It’s crucial to shut down the ScheduledExecutorService once you’re done using it to release resources. This can be done using the shutdown() method.

    executor.shutdown()
    

    Make sure to call shutdown() when you no longer need the ScheduledExecutorService to prevent resource leaks.

  • Putting It All Together

    Here’s a complete example of using ScheduledExecutorService to implement sleep functionality in Kotlin:

    import java.util.concurrent.Executors
    import java.util.concurrent.ScheduledExecutorService
    import java.util.concurrent.TimeUnit
    
    fun main() {
    	val executor: ScheduledExecutorService = Executors.newScheduledThreadPool(1)
    
    	executor.schedule({
    		// Code to execute after the specified delay
    		println("Task executed after delay.")
    	}, 5, TimeUnit.SECONDS)
    
    	executor.shutdown()
    }
    

    In this example, we import the necessary classes, create a ScheduledExecutorService, schedule a task for delayed execution, and then shut down the executor.

    Output:

    Task executed after delay.
    

Using ScheduledExecutorService in Kotlin provides a powerful way to implement sleep functionality. By scheduling tasks for delayed execution, you can effectively introduce time delays in your applications.

Conclusion

This article covers various methods to implement sleep functionality in Kotlin.

It begins by explaining the use of Thread.sleep() to pause the execution of a program for a specified duration. The guide then introduces TimeUnit’s sleep() function, which provides more versatility in controlling delays by accepting different time units.

Next, it explores the delay() function, a feature of Kotlin’s coroutine library designed for asynchronous programming. This function allows for controlled pauses without blocking the thread.

Finally, the guide introduces the ScheduledExecutorService, a powerful tool for scheduling tasks with precise control over when they should run.

With these methods, Kotlin offers a range of options for introducing time delays in your applications, catering to various project requirements and design preferences.

Kailash Vaviya avatar Kailash Vaviya avatar

Kailash Vaviya is a freelance writer who started writing in 2019 and has never stopped since then as he fell in love with it. He has a soft corner for technology and likes to read, learn, and write about it. His content is focused on providing information to help build a brand presence and gain engagement.

LinkedIn