What is volatile keyword in Java

πŸ’‘ Concept: Volatile Keyword

The volatile keyword in Java ensures that changes to a variable are always visible to all threads and prevents instruction reordering by the compiler or CPU.

πŸ“˜ Quick Intro

Marking a variable as volatile ensures it is read from and written directly to main memory, making its latest value visible to all threads instantly.

🧠 Analogy

Imagine a public notice board. If someone writes something on it, anyone passing by can immediately read the latest note. That's what volatile doesβ€”it makes sure everyone sees the same, most recent value.

πŸ”§ Technical Explanation

  • Ensures visibility of updates to a variable across threads.
  • Prevents JVM and CPU from reordering reads/writes for that variable.
  • Does NOT guarantee atomicity (e.g., ++var is still unsafe).
  • Best used for flags, state indicators, or read-write-only variables.
  • Often used in conjunction with while loops for polling.

🎯 Use Cases

  • βœ… Flags to stop background threads (e.g., isRunning).
  • βœ… Simple state indicators shared across threads.
  • βœ… Avoiding stale reads due to caching in multi-core systems.

πŸ’» Example: Volatile Variable


public class VolatileExample {
    private static volatile boolean flag = false;

    public static void main(String[] args) {
        new Thread(() -> {
            while (!flag) {
                // wait
            }
            System.out.println("Flag set!");
        }).start();

        try { Thread.sleep(1000); } catch (InterruptedException e) {}
        flag = true;
    }
}

❓ Interview Q&A

Q1: What is the purpose of volatile?
A: Ensures visibility of changes across threads.

Q2: Does volatile guarantee atomicity?
A: No.

Q3: Can volatile prevent instruction reordering?
A: Yes.

Q4: Is volatile useful in multithreading?
A: Yes.

Q5: Can volatile be used for compound operations?
A: No, use synchronization instead.

Q6: What happens if you don’t use volatile where needed?
A: Threads may see stale values.

Q7: Can static variables be volatile?
A: Yes.

Q8: Is volatile a memory barrier?
A: It behaves like one for that variable.

Q9: Is volatile available since Java 1?
A: Yes.

Q10: Is volatile faster than synchronized?
A: Yes, but use is limited to specific cases.

πŸ“ MCQs

Q1. What does volatile ensure?

  • Atomicity
  • Blocking
  • Visibility across threads
  • Garbage collection

Q2. Does volatile prevent instruction reordering?

  • No
  • Yes
  • Only in Java 5
  • Sometimes

Q3. Is volatile good for compound operations?

  • Yes
  • No
  • Sometimes
  • Depends

Q4. Can you use volatile for flags?

  • No
  • Yes
  • Sometimes
  • Not recommended

Q5. Is volatile keyword thread-safe?

  • Yes
  • No
  • Partially
  • Never

Q6. What happens without volatile in multithreaded flags?

  • Compile error
  • Stale reads
  • Always visible
  • Infinite loops

Q7. Which is stronger, synchronized or volatile?

  • volatile
  • final
  • synchronized
  • transient

Q8. Does volatile affect caching?

  • No
  • Yes
  • Sometimes
  • Only on Windows

Q9. Can static fields be volatile?

  • No
  • Yes
  • Only for objects
  • Only after Java 11

Q10. Which memory area does volatile interact with?

  • Stack
  • Thread-local
  • Main memory
  • Code cache

πŸ’‘ Bonus Insight

Volatile is often misunderstood. While it provides visibility and ordering guarantees, it is not a replacement for synchronization when atomic operations are required.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ” Navigation

Learn More About Java β˜•

What is Java and its key features πŸ‘‰ Explained
Explain the Java Virtual Machine (JVM) πŸ‘‰ Explained
Difference between JDK, JRE, and JVM πŸ‘‰ Explained
What are Java’s main data types πŸ‘‰ Explained
Explain the concept of Object-Oriented Programming in Java πŸ‘‰ Explained
What is the difference between a class and an object πŸ‘‰ Explained
Explain encapsulation with an example πŸ‘‰ Explained
What is inheritance in Java and its types πŸ‘‰ Explained
Define polymorphism in Java with examples πŸ‘‰ Explained
What is abstraction in Java πŸ‘‰ Explained
Difference between abstract class and interface in Java πŸ‘‰ Explained
Explain method overloading and method overriding in Java πŸ‘‰ Explained
What are constructors in Java πŸ‘‰ Explained
What is the use of the static keyword in Java πŸ‘‰ Explained
Explain the difference between final, finally, and finalize in Java πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup