DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Metal and the Simulated Annealing Algorithm
  • Reactive Kafka With Spring Boot
  • Why You Should Migrate Microservices From Java to Kotlin: Experience and Insights
  • How To Create a Homescreen Widget in Android

Trending

  • How to Convert XLS to XLSX in Java
  • The Smart Way to Talk to Your Database: Why Hybrid API + NL2SQL Wins
  • How to Use AWS Aurora Database for a Retail Point of Sale (POS) Transaction System
  • Infrastructure as Code (IaC) Beyond the Basics
  1. DZone
  2. Coding
  3. Languages
  4. Waiting for Coroutines in Kotlin

Waiting for Coroutines in Kotlin

By 
Dan Newton user avatar
Dan Newton
·
May. 12, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
63.8K Views

Join the DZone community and get the full member experience.

Join For Free

Coroutines allow you to execute tasks asynchronously without blocking the calling thread, such as the main thread. Great, but sometimes you will need to wait for all of these tasks to finish. In this post, we will look at how to wait for a coroutine to finish using join.

Note, async/await will not be covered here, as I will cover that in a later post. For now, read the Kotlin docs - Concurrent using async if that is what you are interested in.

How to Get a Job

No, you didn’t misread the heading, I will show you how to get a job:

Kotlin
xxxxxxxxxx
1
 
1
runBlocking {
2
  val job: Job = launch {
3
    delay(2000)
4
    println("and it seems to work!")
5
  }
6
  print("This is your first coroutine, ")
7
}


There, you now have a job. I have solved the world’s employment problems…

Ok, seriously, a Job is returned when you start a coroutine. In fact, from what I understand anyway, the words job and coroutine are interchangeable in this context. Really, they are the same thing, as seen below:

Kotlin
xxxxxxxxxx
1
 
1
@InternalCoroutinesApi
2
public abstract class AbstractCoroutine<in T>(
3
    /**
4
     * The context of the parent coroutine.
5
     */
6
    @JvmField
7
    protected val parentContext: CoroutineContext,
8
    active: Boolean = true
9
) : JobSupport(active), Job, Continuation<T>, CoroutineScope


AbstractCoroutine implements the Job interface. So a coroutine is a job.

What to Do Once You Have a Job

You can control a coroutine through the functions available on the Job interface. Here are some of the functions (there are many more):

  • start
  • join
  • cancel

Further Job operations will be explored in future posts.

Waiting for a Coroutine

To wait for a coroutine to finish, you can call Job.join.

join is a suspending function, meaning that the coroutine calling it will be suspended until it is told to resume. At the point of suspension, the executing thread is released to any other available coroutines (that are sharing that thread or thread pool).

Below is a short example:

Kotlin
xxxxxxxxxx
1
10
 
1
runBlocking {
2
  val job: Job = launch(context = Dispatchers.Default) {
3
    println("[${Thread.currentThread().name}] Launched coroutine")
4
    delay(100)
5
    println("[${Thread.currentThread().name}] Finished coroutine")
6
  }
7
  println("[${Thread.currentThread().name}] Created coroutine")
8
  job.join()
9
  println("[${Thread.currentThread().name}] Finished coroutine")
10
}


In the snippet above, a coroutine is launched, and a Job is returned. join is then called on the created job/coroutine to wait for it to finish before resuming. This leads to the following output:

Plain Text
xxxxxxxxxx
1
 
1
[main] Created coroutine
2
[DefaultDispatcher-worker-1] Launched coroutine
3
[DefaultDispatcher-worker-1] Finished coroutine
4
[main] Finished coroutine


The main thread is blocked while it waits for the job/coroutine to finish. Note, that the main thread is used by runBlocking, while the child is launched using one of the default thread pools.

Just like futures and threads, many coroutines can be created and waited for through the use of join. This is also made slightly easier by the convenient joinAll extension function:

Kotlin
xxxxxxxxxx
1
12
 
1
runBlocking {
2
  val jobs: List<Job> = (1..5).map {
3
    launch(context = Dispatchers.Default) {
4
      println("[${Thread.currentThread().name}] Launched coroutine: $it")
5
      delay(100)
6
      println("[${Thread.currentThread().name}] Finished coroutine: $it")
7
    }
8
  }
9
  println("[${Thread.currentThread().name}] Created all coroutines")
10
  jobs.joinAll()
11
  println("[${Thread.currentThread().name}] Finished all coroutines")
12
}


Something similar to the following would be output:

Plain Text
xxxxxxxxxx
1
12
 
1
[DefaultDispatcher-worker-1] Launched coroutine: 1
2
[DefaultDispatcher-worker-2] Launched coroutine: 2
3
[DefaultDispatcher-worker-3] Launched coroutine: 3
4
[DefaultDispatcher-worker-4] Launched coroutine: 4
5
[main] Created all coroutines
6
[DefaultDispatcher-worker-5] Launched coroutine: 5
7
[DefaultDispatcher-worker-1] Finished coroutine: 1
8
[DefaultDispatcher-worker-4] Finished coroutine: 4
9
[DefaultDispatcher-worker-2] Finished coroutine: 3
10
[DefaultDispatcher-worker-3] Finished coroutine: 5
11
[DefaultDispatcher-worker-5] Finished coroutine: 2
12
[main] Finished all coroutines


I wonder if you can guess what joinAll’s implementation looks like. I don’t have any way to hide text, so I’ll just assume you actually guessed. I have added it below:

Kotlin
xxxxxxxxxx
1
 
1
public suspend fun Collection<Job>.joinAll(): Unit = forEach { it.join() }


Joining Is Not Always Required

Joining all jobs running inside a coroutine is not a requirement to ensure their completion is waited for. By using the coroutineScope builder (a function), you can create a parent/child relationship between coroutines. More precisely, the coroutineScope builder will only progress once all of the coroutines inside it have completed. This is effectively doing a joinAll on all the jobs inside the coroutineScope.

The example below attempts to show this:

Kotlin
xxxxxxxxxx
1
22
 
1
runBlocking {
2
  val jobs: List<Job> = (1..2).map { parentNumber ->
3
    // This coroutine is joined on inside [runBlocking] to allow the last [println]
4
    launch(context = Dispatchers.Default) {
5
      // The [coroutineScope] block cannot be left until the 2 corountines launched inside have finished
6
      coroutineScope {
7
        println("[${Thread.currentThread().name}] Launched parent: $parentNumber")
8
        (1..2).map { childNumber ->
9
          launch {
10
            println("[${Thread.currentThread().name}] Launched child: $parentNumber - $childNumber")
11
            delay(100)
12
            println("[${Thread.currentThread().name}] Finished child: $parentNumber - $childNumber")
13
          }
14
        }
15
      }
16
      println("[${Thread.currentThread().name}] Finished parent: $parentNumber")
17
    }
18
  }
19
  println("[${Thread.currentThread().name}] Created all coroutines")
20
  jobs.joinAll()
21
  println("[${Thread.currentThread().name}] Finished all coroutines")
22
}


Which outputs something like this:

Plain Text
xxxxxxxxxx
1
14
 
1
[DefaultDispatcher-worker-1] Launched parent: 1
2
[main] Created all coroutines
3
[DefaultDispatcher-worker-2] Launched parent: 2
4
[DefaultDispatcher-worker-3] Launched child: 2 - 1
5
[DefaultDispatcher-worker-4] Launched child: 1 - 1
6
[DefaultDispatcher-worker-5] Launched child: 1 - 2
7
[DefaultDispatcher-worker-3] Launched child: 2 - 2
8
[DefaultDispatcher-worker-2] Finished child: 2 - 1
9
[DefaultDispatcher-worker-3] Finished child: 2 - 2
10
[DefaultDispatcher-worker-5] Finished child: 1 - 2
11
[DefaultDispatcher-worker-1] Finished child: 1 - 1
12
[DefaultDispatcher-worker-2] Finished parent: 2
13
[DefaultDispatcher-worker-1] Finished parent: 1
14
[main] Finished all coroutines


Each parent coroutine had to wait until their children finished. This was enabled by using coroutineScope, ensuring each coroutine launched inside it had completed before moving on.

I only touched on this subject to show that joining is not the only way to wait for jobs to finish. For some more information, have a look at the Kotlin docs - Scope builder.

Summary

Sometimes you will want to wait for several coroutines to complete before moving on. This behavior can be achieved using join and joinAll provided by the Job interface. Doing so will suspend the calling coroutine until the joined jobs have concluded. Similar behavior can also be obtained via the coroutineScope builder, ensuring that all jobs launched within it have ended before continuing.


If you enjoyed this post or found it helpful (or both) then please feel free to follow me on Twitter at @LankyDanDev and remember to share with anyone else who might find this useful!

Kotlin (programming language)

Published at DZone with permission of Dan Newton, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Metal and the Simulated Annealing Algorithm
  • Reactive Kafka With Spring Boot
  • Why You Should Migrate Microservices From Java to Kotlin: Experience and Insights
  • How To Create a Homescreen Widget in Android

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!