Week 20 — What Is the volatile keyword in java?
Question of the Week #20
What Is the volatile keyword in java?
7 Replies
Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem.
Submission from Corvipes#4980
Volatile keyword brings value will be always keep in application memory. Which is why each thread sees newest value. There is usually uses in multithread.
Example:
public static volatile boolean stopFlag = false;
Submission from Piotr Łyszkowski#0456
In java , volatile keyword ensure that variable is always read and written from main memory.
Submission from Amol#5270
Multiple threads can change a variable's value by using the volatile keyword. Making classes thread safe is another use for it. It means that using a method or an instance of a class by several threads is not problematic. Both primitive types and objects are compatible with the volatile keyword.
Submission from OfficialMandarin#1428
Changing a variable from one thread may not apply that change to another thread if there is no "happens-before" relation between the accesses of the variable.
For example, the following piece of code may never terminate (but it could):
The keyword
volatile
marks a variable to be visible to other threads immediately when updated. If that keyword is added to the variable loop
in the above example, Java will make sure that changing the variable is picked up by the loop:
⭐ Submission from dan1st#7327