Hello, I read kotlin docs and it says that object ...
# getting-started
ö
Hello, I read kotlin docs and it says that object declaration is thread safe. But then why we use volatile and synchronized keywords in companion object? I thought object declariton is not thread safe and we should use that structure in companion object.
y
the object itself is thread-safe, as in you're guaranteed that you'll get the same object across threads, but there's no guarantee as to the data itself inside the object
👍 1
ö
So, is it a good case for data thread safe? Object A { @Volatile var count = 0 }
n
Copy code
guaranteed that you'll get the same object across
Unless you serialize\deserialize object and end up with 2
object
instances (should be fixed in 1.9.0)
y
It's not actually fixed. Instead, the == checks are fixed
n
@Youssef Shoaib [MOD] Hm interesting, thank you for clarification
@Ömer Sungur thread safe is quite vague concept, depends on what you want to achieve with this code
ö
I mean only being able to access it from one place
n
Still not sure what it means
Copy code
Marks the JVM backing field of the annotated var property as volatile, meaning that reads and writes to this field are atomic and writes are always made visible to other threads. If another thread reads the value of this field (e.g. through its accessor), it sees not only that value, but all side effects that led to writing that value.
@Ömer Sungur What does it mean “from one place”?
ö
I think this means that when a change is made , that change is valid in all threads.
I mean in method or class.
n
It will not be cached, but resulting value still could be inconsistent if you will increment it from different threads. Increment = read\increment\write, 3 operations. You probably will need to use AtomicInt or
synchronized
block to increment this counter.
ö
Okay thank you for replying @Nick Kleban