Volatile

Java also offers the volatile keyword, which when applied to a field of a class instructs the CPU to always read it from the RAM and not from the CPU cache. It also prevents instructions reordering; it acts as a memory barrier. The same as with the synchronized methods, in Kotlin you apply the annotation to a property to have the same effect as Java’s volatile keyword:

@Volatile
private var counter = 0

But be careful with this construct, as often it is not enough to achieve thread safety. For example, if we have a method that increments this field and more than one thread accesses this method, it could lead to unpredictable results. Incrementing an integer consists of more than one action: first, a variable has to be read from the memory, then it can be incremented and written back to the memory. To achieve thread safety, these actions have to be atomic, and volatile doesn't have that guarantee. So, if you are not familiar with the details of the Java memory model, it is better to use synchronized blocks. Uncontended locks have a negligible performance impact and are a lot harder to get wrong.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.144.100