WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Advanced · question 58 of 100

Explain the purpose of the @Volatile annotation in Kotlin. When should you use it?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, the ‘@Volatile‘ annotation is used to indicate that a variable’s value may be modified by multiple threads, so the compiler should avoid optimizing code that accesses that variable. When a variable is marked as ‘@Volatile‘, it guarantees that the value of the variable is retrieved from main memory each time it is accessed, rather than relying on a thread’s cache, which could result in stale data being used.

In other words, ‘@Volatile‘ is used to provide thread-safety for shared mutable state. Without it, a change to a given variable in one thread may not be immediately visible in another thread due to thread caching issues. Using ‘@Volatile‘ forces the compiler to treat the variable differently, ensuring that writes made to it are immediately visible in all threads that access it.

Here is an example that demonstrates the use of ‘@Volatile‘:

class Example {
    @Volatile var counter = 0

    fun run() {
        for (i in 1..100_000) {
            counter++
        }
    }
}

fun main() {
    val example = Example()

    val thread1 = Thread { example.run() }
    val thread2 = Thread { example.run() }

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

    println(example.counter)  // Expected output: 200000
}

In this example, we create an ‘Example‘ class with a ‘counter‘ variable marked with ‘@Volatile‘. We then create two threads that call the ‘run‘ function of ‘example‘ simultaneously. If we didn’t declare ‘counter‘ as ‘@Volatile‘, we would not be guaranteed to see the full count of both threads - some changes might be lost due to caching. However, because we declared it as ‘@Volatile‘, we know that the variable will always represent the true count of both threads combined.

In summary, ‘@Volatile‘ should be used whenever you have a mutable variable that may be accessed by multiple threads. It ensures that changes made to that variable are always visible to all threads that access it, helping you to avoid race conditions and other thread-safety issues.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics