Java MCQ: Which of the following is true about the ‘volatile’ keyword in Java?
Answer:
Explanation:
The volatile
keyword in Java is used to indicate that a variable’s value will be modified by different threads. It ensures that the value of the variable is always read from and written to the main memory, rather than being cached in a thread’s local cache. This ensures visibility of changes made to the variable across all threads.
However, volatile
does not provide atomicity, meaning that operations on volatile variables are not guaranteed to be thread-safe. For atomicity, other mechanisms like synchronized blocks or atomic classes from the java.util.concurrent
package should be used.
Understanding the volatile
keyword is important for managing concurrency in Java, especially when dealing with variables shared between multiple threads.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html