What is the volatile keyword useful for?

前端 未结 23 2661
闹比i
闹比i 2020-11-21 05:32

At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation.

Given the detail in which that arti

23条回答
  •  醉梦人生
    2020-11-21 06:00

    The volatile key when used with a variable, will make sure that threads reading this variable will see the same value . Now if you have multiple threads reading and writing to a variable, making the variable volatile will not be enough and data will be corrupted . Image threads have read the same value but each one has done some chages (say incremented a counter) , when writing back to the memory, data integrity is violated . That is why it is necessary to make the varible synchronized (diffrent ways are possible)

    If the changes are done by 1 thread and the others need just to read this value, the volatile will be suitable.

提交回复
热议问题