August 2018
Beginner
178 pages
4h 56m
English
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:
@Volatileprivate 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 ...
Read now
Unlock full access