Volatile Keyword— Java

Jainil Gada
2 min readFeb 3, 2021

Volatile — If field is declared as volatile in Java, every thread accessing the field will read the current value, i.e value from the main memory and not from the cache.

Multi-Core CPU

In today’s word, we use computers with multi-core CPU, which have capacity to execute multiple tasks/program in parallel. Many of the applications are programmed in a way that they make full utilization of the power offered by CPU. With the development in the field of parallel programming, parallel processing is also achieved through hardware parallelism i.e. executing two processes on two separate CPU cores simultaneously.

In multi core CPU, all cores share same main memory. Tasks can be processed on multiple core simultaneously. In order to increase the speed and performance, each core have its own set of cache’s like L1,L2 cache.

Multi Core CPU
Source — https://insights.sei.cmu.edu/

Problem

Let say we have 2 threads T1 and T2, and they have shared variable ‘x’. Both threads will load the variable in their own cache. Now let’s say Thread T1 updates the value of variable ‘x’ and write it to main memory. But T2 will not read that value from main memory instantaneously. As it already have variable ‘x’ already in its cache.

Solution

To solve such problem of visibility, we make use of volatile keyword in Java. By declaring field as variable, Java ensures that whenever it reads/writes value of volatile field, it reads/writes from the main memory and not from the cache. So that all threads have current/latest value of shared field.

--

--