What is the volatile keyword useful for?

前端 未结 23 2703
闹比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条回答
  •  Happy的楠姐
    2020-11-21 06:15

    From oracle documentation page, the need for volatile variable arises to fix memory consistency issues:

    Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

    This means that changes to a volatile variable are always visible to other threads. It also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

    As explained in Peter Parker answer, in absence of volatile modifier, each thread's stack may have their own copy of variable. By making the variable as volatile, memory consistency issues have been fixed.

    Have a look at jenkov tutorial page for better understanding.

    Have a look at related SE question for some more details on volatile & use cases to use volatile:

    Difference between volatile and synchronized in Java

    One practical use case:

    You have many threads, which need to print current time in a particular format for example : java.text.SimpleDateFormat("HH-mm-ss"). Yon can have one class, which converts current time into SimpleDateFormat and updated the variable for every one second. All other threads can simply use this volatile variable to print current time in log files.

提交回复
热议问题