Tuesday 17 November 2015

What is the use of volatile keyword

When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever threads are updating the values, it is updated to the main memory. So, other threads can access the updated value. Use Volatile keyword whenever the variable represents some type of system or environment dependent variable. For Example: clocks and simple counters.

No comments:

Post a Comment