Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the volatile keyword in Java? When and why should you use it? Java में volatile keyword क्या है? कब और क्यों use करते हैं?

Answer

The volatile keyword ensures that a variable's value is always read from main memory and written to main memory immediately, preventing CPU cache issues and ensuring visibility between threads.

// Problem: Without volatile
public class VolatileDemo {
    private boolean flag = false;
    
    public static void main(String[] args) {
        VolatileDemo demo = new VolatileDemo();
        
        // Thread 1: Loop reading flag
        new Thread(() -> {
            while (!demo.flag) {
                // May never see flag=true (cached)
            }
            System.out.println('Flag is true');
        }).start();
        
        // Thread 2: Set flag after delay
        new Thread(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {}
            demo.flag = true;
            System.out.println('Flag set to true');
        }).start();
    }
}

// Solution: Use volatile
public class VolatileFix {
    private volatile boolean flag = false;  // Keyword added
    
    public static void main(String[] args) {
        VolatileFix demo = new VolatileFix();
        
        // Thread 1
        new Thread(() -> {
            while (!demo.flag) {
                // Reads from main memory every time
            }
            System.out.println('Flag is true');
        }).start();
        
        // Thread 2
        new Thread(() -> {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {}
            demo.flag = true;
            System.out.println('Flag set to true');
        }).start();
    }
}

// Volatile guarantees:
// 1. Visibility - all threads see latest value
// 2. Atomicity - only for read/write (not ++ operation)
// 3. No caching - always read from main memory

// When NOT to use volatile:
// - Complex operations (use synchronized)
// - Compound operations like ++ (use Atomic classes)
// - Multiple fields (use synchronized)

// Better alternative: Atomic classes
import java.util.concurrent.atomic.AtomicBoolean;

public class AtomicExample {
    private AtomicBoolean flag = new AtomicBoolean(false);
    
    public static void main(String[] args) {
        AtomicExample demo = new AtomicExample();
        
        new Thread(() -> {
            while (!demo.flag.get()) {
                // Thread-safe reading
            }
        }).start();
        
        new Thread(() -> {
            demo.flag.set(true);
        }).start();
    }
}
Volatile Keyword:

Problem: CPU cache
- Thread अपना local cache use करता है
- Main memory update नहीं दिखता

Solution: volatile
private volatile boolean flag;

Guarantees:
1. Visibility - all threads see latest value
2. No caching - always main memory
3. NOT atomic (++ नहीं करो)

When to use:
- Single boolean/flag checks
- Visibility guarantee चाहिए

When NOT to use:
- Complex operations
- Use synchronized या Atomic classes

Comparison:
volatile: Fast, limited
AtomicBoolean: Thread-safe, comprehensive
synchronized: Slowest, most control

Was this answer clear?