Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable.
Suppose a variable 'x' is being used by thread1 and thread2. Now thread1 applies some algorithm which uses 'x' and the algorithm requires that the value of the variable 'x' can not change unless changed by some operation in the algorithm(which is usually the case) , but in reality the value of 'x' can get changed by an operation in thread2. So in this case 'volatile' keyword is helpful, it will specify that the value of the variable 'x' can get changed automatically, so it will prevent any such algorithms that assume that 'x' can't change unless changed on purpose.
- cheeseburger February 09, 2013