← Back to libraryQuestion 34 of 273
JavaAdvanced

Volatile Keyword

📖 Detailed Explanation:

The volatile keyword ensures 'Visibility' in multithreading. Normally, threads cache variables locally. Marking a variable volatile forces the thread to always read from and write to main memory. This ensures all threads see the most recent value immediately. However, volatile does NOT guarantee atomicity (all-or-nothing execution).

🎯 Scenario-Based Interview Question:

Why is 'volatile' not enough for a thread-safe counter? Provide an example.

💡 Note:

Volatile is good for boolean flags but NOT for counters (like count++). For counters, use synchronized or AtomicInteger.