Volatile properties in Kotlin?

Kotlin

Kotlin Problem Overview


How does one mark a var in Kotlin volatile?

volatile public var tmpEndedAt: Long? = null

Is giving me the error: "unresolved reference: volatile".

Kotlin Solutions


Solution 1 - Kotlin

I decided to give Kotlin a shot by just using the "convert java to kotlin" function in IntelliJ. Apparently that set things up wrong.

I tried doing the same thing, but after applying the Kotlin Gradle plugin and placing the file in src/kotlin and it all worked. Thanks for the help anyway guys.

The code would be:

@Volatile var tmpEndedAt: Long? = null

Solution 2 - Kotlin

According to the Kotlin documentation Kotlin-@Volatile

> Marks the JVM backing field of the annotated property as volatile, meaning that writes to this field are immediately made visible to other threads.

So, in Kotlin you can mark the property as volatile with @Volatile annotation.

e.g.

@Volatile var tmpEndedAt: Long? = null

Solution 3 - Kotlin

In kotlin in order to force changes in a variable to be immediately visible to other threads, we can use the annotation @Volatile. If a variable is not shared between multiple threads, you don't need to use volatile keyword with that variable.

In other words, When you apply volatile to a field of a class, It 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.

check here for more information :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew CholakianView Question on Stackoverflow
Solution 1 - KotlinAndrew CholakianView Answer on Stackoverflow
Solution 2 - KotlinWaqar UlHaqView Answer on Stackoverflow
Solution 3 - KotlinNazanin NasabView Answer on Stackoverflow