69

How does one mark a var in Kotlin volatile?

volatile public var tmpEndedAt: Long? = null

gives me the error:

"unresolved reference: volatile"

Rachid K.
  • 4,490
  • 3
  • 11
  • 30
Andrew Cholakian
  • 4,392
  • 3
  • 26
  • 27

3 Answers3

84

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
akhy
  • 5,760
  • 6
  • 39
  • 60
Andrew Cholakian
  • 4,392
  • 3
  • 26
  • 27
  • I have encountered this problem before. Here's an issue, I just created: https://youtrack.jetbrains.com/issue/KT-7986 – Kirill Rakhman Jun 09 '15 at 08:56
  • Will it be compiled even without `kapt`? I'm asking because I have a lot of old Java classes with many lombok annotations so I can't use `kapt` with that or it breaks everything. – Vrakfall Jun 22 '19 at 10:08
17

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.

Snostorp
  • 544
  • 1
  • 8
  • 14
Nazanin Nasab
  • 595
  • 8
  • 18
15

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
Community
  • 1
  • 1
Waqar UlHaq
  • 6,144
  • 2
  • 34
  • 42