Volatile properties in Kotlin?

39.5k Views Asked by At

How does one mark a var in Kotlin volatile?

volatile public var tmpEndedAt: Long? = null

gives me the error:

"unresolved reference: volatile"

3

There are 3 best solutions below

2
On BEST ANSWER

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
0
On

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.

I.e. 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 Volatile in O’Reilly's Kotlin Quick Start Guide for more information.

0
On

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