The Java Memory Model (JMM) Interview Questions
KOTLIN › JVM Concurrency
What does the volatile keyword do in Java and Kotlin, and what doesn't it do?
What a strong answer covers: @Volatile guarantees visibility: a write by one thread is seen by subsequent reads in other threads, and it prevents certain reorderings around the access. It does not make compound operations atomic: count++ on a volatile is still a read-modify-write race. Use AtomicInteger or a lock for that.
What is the happens-before relationship, and why does it matter?
What a strong answer covers: Happens-before is the Java Memory Model rule that guarantees one action's effects are visible to another. Without it, threads can see stale values or reordered writes because of CPU caches and compiler reordering. It's established by synchronized blocks (unlock before a later lock of the same monitor), volatile writes before later reads, Thread.start, Thread.join, and concurrent collections.
What is a race condition versus a data race? Give an Android example.
What a strong answer covers: A data race is two threads accessing the same memory without synchronisation, at least one writing, so results depend on unspecified ordering. A race condition is a logic bug where correctness depends on timing, even with synchronisation, like check-then-act. Example: two coroutines on Dispatchers.Default incrementing a shared counter lose updates, or checking 'if cache is empty, fetch' twice concurrently triggers duplicate network calls.
Why is double-checked locking broken without volatile, and how does Kotlin's lazy avoid it?
What a strong answer covers: Without volatile, the write of the instance reference can be reordered before the constructor finishes, so another thread can see a non-null but partially built object. Declaring the field volatile prevents that. Kotlin's lazy(SYNCHRONIZED) uses a volatile field with double-checked locking internally, so it's safe and you don't need to write it.
Explain what safe publication means and how final fields in the JMM help immutable objects be thread-safe.
What a strong answer covers: Safe publication means making an object visible to other threads so they see it fully constructed: via a volatile field, a final field, a lock, or a concurrent collection. Final fields have special JMM semantics: once a constructor finishes (without leaking 'this'), any thread that sees the object reference sees the correct final field values without synchronisation. That's why immutable objects with val fields can be shared freely.