When you read data from one thread but write the data from a different thread, you can run into a problem where the thread reading the data will read stale/incorrect data.

You can prevent this behavior by marking the data field in question with the volatile keyword. This indicates to the compiler that no optimizations should be done with respect to the storage location of this field and will prevent the problem of reading stale data.

Below is the earlier example, updated to include the volatile keyword.