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

170
Visualizações
Are Kotlin channels used in coroutines thread safe / synchronized / keep happens-before relationship?

Are the functions available in Kotlin channels thread safe? e.g.

val channel = Channel<Boolean>()
val job1 = GlobalScope.launch {
    channel.send(true)
}
val job2 = GlobalScope.launch {
    val x = channel.poll()
}

If in the above code job1 was executed by the machine (in real time) before job2 is executed and on different threads, is it guaranteed that x is set with true? Or is it possible that it gets set with null (because cpu cache was not updated)?

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

0

Channel class kotlinx.coroutines library is thread-safe. It is designed to support multiple threads.

GlobalScope.launch may not necessarily mean a coroutine will be executed in a new thread

over 4 years ago · Santiago Trujillo Relatório

0

If in the above code job1 was executed by the machine (in real time) before job2 is executed and on different threads, is it guaranteed that x is set with true? Or is it possible that it gets set with null (because cpu cache was not updated)?

The Java Memory Model has no notion of time and it doesn't guarantee anything just based on the fact that a line executed earlier than another one. You can't even ascertain when an action was executed on a CPU.

In the code you posted, there are two concurrently executing coroutines. If and only if channel.poll() gets a non-null value, there is a happens-before edge going from send() to poll(). If it gets a null-value, there is no happens-before edge.

Let's say you determine the wall-clock time in the two coroutines, something like the following:

var sendTime: Long = 0
var receiveTime: Long = 0

suspend fun main() {
    val channel = Channel<Boolean>(UNLIMITED)
    val job1 = GlobalScope.launch {
        channel.send(true)
        sendTime = System.nanoTime()
    }
    val job2 = GlobalScope.launch {
        receiveTime = System.nanoTime()
        val x = channel.poll()
        println(x)
    }
    job1.join()
    job2.join()
    println("${receiveTime - sendTime}")
}

The fact that receiveTime is greater than sendTime does not induce a happens-before relationship and it doesn't force channel.poll() to observe the sent item. Calling nanoTime() is not a synchronization action.

Note that these facts have nothing to do Kotlin or coroutines specifically, this is how the Java Memory Model works. If you study the C++ memory model, you'll find it works the same way.

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