https://kotlinlang.org logo
Title
m

Minsoo Cheong

10/13/2021, 5:31 AM
Hi guys, is alteration to different fields of a same object thread - safe? lets say I have this dto class:
data class Example(
var fieldA: Int,
var fieldB: Int
)
and that i change fieldA in thread 1 and fieldB in thread 2 (of a same object of class Example). would this be thread-safe? and if not so, how would I achieve thread safety?
j

Joffrey

10/13/2021, 8:41 AM
It is thread safe, yes.
🙇 2
:thank-you: 1
a

aidanvii

10/13/2021, 11:51 AM
it’s thread safe, but poor design
There is a saying:
Don’t communicate by sharing memory; share memory by communicating.
👀 3
d

DALDEI

10/18/2021, 10:34 PM
Whether it is 'thread safe' or not depends on what your use requies. You will not corrupt either fieldA nor fieldB, But neither will you guarentee which order they are set in ( or which order they will appear to be set in ) when reading from a different thread. That matters if the 2 variables are dependant. Imagine they are "hours" and "minutes" and a consumer wants to know the 'current time' If the writer and reader are in different threads the JVM does not guarantee that the reader thread will observe the same order of writing (in all cases). If it started out as ( 1 , 59) then a writer added 1 minute so set to (2,0) as 2 assignments ( hour=(hour+1 mod 24) min = (min + 1) mod 60 ) A reader may observe any of (1,59) , (2,59) , (1,0) or (2,0)
❤️ 1
m

Minsoo Cheong

10/27/2021, 8:54 AM
thanks a lot! fortunately, my usecase doesn't include time or order-dependent multiple fields
d

DALDEI

10/29/2021, 1:19 AM
As long as you stick to Primative types or references , and not using 1 'mulit thread' variable to determine the correct value for another , should be fine. Note: not sure if long counts