This tutorial demonstrates how to create Kotlin coroutines and debug them using IntelliJ IDEA.
The tutorial assumes you have prior knowledge of the coroutines concept.
Open a Kotlin project in IntelliJ IDEA. If you don't have a project, create one.
To use the kotlinx.coroutines
library in a Gradle project, add the following dependency to build.gradle(.kts)
:
dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:%coroutinesVersion%") }
dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:%coroutinesVersion%' }
For other build systems, see instructions in the kotlinx.coroutines
README.
Open the Main.kt
file in src/main/kotlin
.
The src
directory contains Kotlin source files and resources. The Main.kt
file contains sample code that will print Hello World!
.
Change code in the main()
function:
runBlocking()
block to wrap a coroutine.async()
function to create coroutines that compute deferred values a
and b
.await()
function to await the computation result.println()
function to print computing status and the result of multiplication to the output.import kotlinx.coroutines.* fun main() = runBlocking<Unit> { val a = async { println("I'm computing part of the answer") 6 } val b = async { println("I'm computing another part of the answer") 7 } println("The answer is ${a.await() * b.await()}") }
Build the code by clicking Build Project.
Set breakpoints at the lines with the println()
function call:
Run the code in debug mode by clicking Debug next to the run configuration at the top of the screen.
The Debug tool window appears:
Resume the debugger session by clicking Resume Program in the Debug tool window:
Now the Coroutines tab shows the following:
a
value – it has the RUNNING status.b
.Resume the debugger session by clicking Resume Program in the Debug tool window:
Now the Coroutines tab shows the following:
b
– it has the RUNNING status.Using IntelliJ IDEA debugger, you can dig deeper into each coroutine to debug your code.
If you use suspend
functions, in the debugger, you might see the “was optimized out” text next to a variable's name:
This text means that the variable‘s lifetime was decreased, and the variable doesn’t exist anymore. It is difficult to debug code with optimized variables because you don't see their values. You can disable this behavior with the -Xdebug
compiler option.
Never use this flag in production:
-Xdebug
can cause memory leaks.
{type=“warning”}