https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
g

Grigorii Yurkov

05/22/2022, 10:42 AM
Are coroutines really thread safe? As far as I understand this code can potentially print
0
. Because
i
can be modified from different threads and kotlin compiler doesn't mark it as
volatile
under the hood
j

Joffrey

05/22/2022, 10:47 AM
Just curious, how did you implement
switchThread()
, and which dispatcher are you running
check()
in? Are you using
Unconfined
?
g

Grigorii Yurkov

05/22/2022, 10:48 AM
I don't use std lib here
Even if I used
Dispatcher
from std lib, I also could get this code run on different threads, because `Dispatcher`s have many threads under the hood
u

uli

05/22/2022, 11:06 AM
If you use e.g. withContext the compiler will take care of memory barriers. If you build your own context switching you have to take care of memory consistency yourself.
j

Joffrey

05/22/2022, 11:06 AM
I don't think it should be a problem either way. The way suspension is implemented is via a state machine and a switch statement. So different parts of the code here are actually not even reading/writing the same local variable
i
. Each of the 3 sections of the
check
method are run during 3 different invocations of that method, each of which defining their own local
i
. The first section sets it to 0 and stores it in the continuation, the other 2 invocations initialize their own
i
from the continuation object.
e

ephemient

05/22/2022, 11:11 AM
with the JVM memory model, all reads and writes are ordered with respect to synchronization. so as long as
switchThread()
synchronizes,
i
is safe
u

uli

05/22/2022, 11:11 AM
@Joffrey the question is about the JVM memory model which does not guarantee visibility of changes across threads in general. Translated to a physical memory model this boils down to cache coherency. I.e each thread might run on a different core with is own hardware cache. And the changes of i++ might not have been synced to the cache of the core running the new thread when it tries to read the result
e

ephemient

05/22/2022, 11:13 AM
if
switchThread()
does not involve any synchronization or volatile operations, then indeed an older value of non-volatile
i
could be observed
g

Grigorii Yurkov

05/22/2022, 11:13 AM
@Joffrey I think you are wrong that there are multiple instances of
i
, because kotlin compiler optimizes code and create just 1 instance of
Continuation
where our
i
is stored
e

ephemient

05/22/2022, 11:15 AM
kotlinx.coroutines is always safe as it performs atomic operations at critical points
j

Joffrey

05/22/2022, 11:17 AM
@Grigorii Yurkov if you read carefully what I wrote, I was referring to 3 different local variables
i
, but a single continuation to/from which the value of the local `i`s are read/written. So marking the local
i
volatile would be pointless. I might be wrong in concluding that solves the problem though (I just checked that the synthetic
Continuation
fields are not marked volatile either)
g

Grigorii Yurkov

05/22/2022, 11:18 AM
@ephemient how can I fix my
switchThread()
so it becomes thread safe? Because I don't see how it's possible. And I don't understand how std lib makes it thread safe
e

ephemient

05/22/2022, 11:20 AM
@Grigorii Yurkov honestly I think it's harder to make it non-thread-safe than it is to make it thread-safe. if you have an atomic run queue then it just works
g

Grigorii Yurkov

05/22/2022, 11:21 AM
@Joffrey Reread your comment again - yes I agree with you. Except in the part that there is no problem here
👍 1
e

ephemient

05/22/2022, 11:24 AM
e.g. if you are adding the paused continuation to a queue that another thread reads from to schedule and run, that must be synchronized for thread-safety, and that synchronization will force the reads and writes of
i
to be observed in the right order as well, even with its field in
Continuation
being non-volatile
g

Grigorii Yurkov

05/22/2022, 11:28 AM
@ephemient So you're trying to say, If I go to
Dispatcher
sources I will find synchronization there?
e

ephemient

05/22/2022, 11:29 AM
it's mostly hidden by
kotlinx.atomicfu
but yes
u

uli

05/22/2022, 11:34 AM
What are you trying to achieve in the first place? Would
yield
serve your purpose?
1
g

Grigorii Yurkov

05/22/2022, 11:39 AM
@uli I am trying to understand how std lib manages to be thread safe. The code is just an example to explain my point why I consider coroutines not thread safe by default
u

uli

05/22/2022, 11:40 AM
I see. Nobel purpose 🙂
e

ephemient

05/22/2022, 11:40 AM
https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
(regardless of whether x and y are volatile or not, if x occurs before y on a single thread, then they are ordered)
If an action x synchronizes-with a following action y, then we also have hb(x, y).
(is what defines happens-before edges across threads) so while non-volatile reads and writes between threads have no defined ordering relative to each other, once you add any synchronization then everything that was ordered before it, is also ordered before anything after it
anyway this is a lot of text to just say "they thought of that, Kotlin + kotlinx.coroutines makes it easy to write safe code". if you are writing your own non-kotlinx.coroutines coroutine framework then sure, you may need to worry about this…
g

Grigorii Yurkov

05/22/2022, 11:51 AM
@ephemient Yes, I understand that std lib developers are not stupid people who cannot write thread safe code. It's me who don't understand how it works. But you showed me the direction I need to learn more, thank you
e

ephemient

05/22/2022, 12:38 PM
@Grigorii Yurkov here's an demo of a coroutine dispatcher that is not thread safe. but note that it has obvious data races. kotlinx.coroutines doesn't https://pl.kotl.in/dEqx_fqfM
g

Grigorii Yurkov

05/22/2022, 12:45 PM
@ephemient Does changing queue with BlockingQueue make it safe?
e

ephemient

05/22/2022, 12:49 PM
with appropriate changes, yes
s

streetsofboston

05/22/2022, 12:51 PM
@Grigorii Yurkov Not sure how that is implemented under the hood, but your local
var i
is safe from race conditions. Coroutines guarantee that you can call suspend funs sequentially safely and not worry about race conditions and volatility.
g

Grigorii Yurkov

05/22/2022, 12:52 PM
@ephemient This makes reading/writing from
queue
safe, but I don't see why reading and writing from
i
becomes safe😞
e

ephemient

05/22/2022, 12:52 PM
@streetsofboston the suspend function translation of a "local"
var i
actually becomes part of the heap (in the generated
Continuation
). we are discussing how Kotlin makes that safe, because it's actually not the same safety as you have with a local variable
👍 1
1
@Grigorii Yurkov because writing to a synchronized queue forces
i
to be committed, and reading from a synchronized queue forces the updated
i
to be observed
we have
hb(i++, queue.put())
on one thread,
hb(queue.put(), queue.take())
across threads, and
hb(queue.take(), i)
on the new thread
g

Grigorii Yurkov

05/22/2022, 12:58 PM
I think I need to read when thread decides to put field from cache back to common memory or update cache from common memory
e

ephemient

05/22/2022, 12:59 PM
how the JVM implements that varies by platform, but the JLS does specify what implementations must provide
for BlockingQueue, that happens-before link would be covered by https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility
:thank-you: 1