#607 – When Do You Need the volatile Keyword?

The volatile keyword attached to a data field tells the compiler that this field may be read or written to by one or more threads at any time.  Values read from the field are therefore dependent on the timing of the different threads that might be writing to the field.  You can also think of it this way–the value of the field is “volatile”–it could change at any time, so the compiler should not make assumptions about the field’s value being static that would lead to incorrect optimizations.  I.e. Optimizations that lead to a thread reading a stale/incorrect value.

So you need to mark a field as volatile when

  • Different threads read and write the field’s value
  • You don’t protect access to the field using some synchronization technique (e.g. lock statement)