Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

451
Visualizações
Kotlin Coroutines: one single coroutine at a time in single thread

Consider this code below, I'm trying to use Executors.newFixedThreadPool(1).asCoroutineDispatcher() to create a single thread dispatcher; I want code within launch(singleThread){...} to be executed sequentially

expected result should be like below because async-block#2 reach/acquire singleThread first

async block #2
async block #1
single thread block #2
single thread block #1
The answer is 3

but the actual result is

async block #2
async block #1
single thread block #1
single thread block #2
The answer is 3

single-thread-block-#2 and single-thread-block-#1 seem to run in parallel, singleThread makes no different here

import java.util.concurrent.Executors
import kotlinx.coroutines.*
import kotlin.system.*

val singleThread = Executors.newFixedThreadPool(1).asCoroutineDispatcher()

fun main() = runBlocking<Unit> {
    val time = measureTimeMillis {
        val one = async { // async block #1
            delay(200)
            println("async block #1")
            launch (singleThread) {
                delay(500)
                println("single thread block #1")
            }
            2
        }
        val two = async { // async block #2
            delay(100)
            println("async block #2")
            launch (singleThread) {
                delay(1500)
                println("single thread block #2")
            }
            1
        }
        println("The answer is ${one.await() + two.await()}")
    }
    println("Completed in $time ms")
}

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Mind the delay() is suspend function in the code. It is implemented via coroutine suspension. It means that the execution of the code is suspended at the moment when you call the delay and only resumed after the timeout. The thread (for example one that you use via async(singleThread) {..} is not busy waiting to the time to elapse.

The overall scenario looks like that

  • ...
  • the "async block #2" printed
  • task 2 is running on the singleThread
  • task 2 is suspended with delay(1500), the singleThread is free
  • task 1 is started on the singleThread
  • task 1 is suspended with delay(500), the singleThread is free
  • at that point we have the delay queue:
    • resume the delay(500) for task 1
    • resume the delay(1500) for task 2
  • after some time
  • resume(500) schedules the second part of task 1 to run in the singleThread
  • after some time
  • resume(1500) schedules the second part of task 2 to run in the singleThread
over 4 years ago · Santiago Trujillo Relatório

0

In addition to the @EugenePetrenko answer the is a new method CoroutineDispatcher.limitedParallelism(numberOfParallelism), which you can use to guarantees the parallelism restriction - at most 1 coroutine can be executed concurrently in this dispatcher. It will look like:

val singleThread = Dispatchers.IO.limitedParallelism(1)

someCoroutineScope.launch (singleThread) {
    ...
}

Function limitedParallelism is available starting from the 1.6.0 version of the kotlinx.coroutines library.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda