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)?
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
If in the above code
job1was executed by the machine (in real time) beforejob2is executed and on different threads, is it guaranteed thatxis set withtrue? Or is it possible that it gets set withnull(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.