0
votes

From Java Concurrency in Practice

Threads share the memory address space of their owning process, all the threads within a process have access to the same variables & allocate objects from the same heap.

Also

Declaring a variable as volatile means that threads should not cache such a variable or in other words should not trust the values of these variables unless they are directly read from the main memory.

My question is

Say there is a non-volatile instance variable 'a' which is modified by a thread. Won't the modified value of 'a' be updated on the heap. If it is updated on the heap another thread reading that instance variable would automatically read the updated value as threads share the instance variables from the heap. So how is the functioning of a volatile variable different?

1

1 Answers

3
votes

The difference is that a volatile variable is forced to be flushed from all caches before reading and all reads come from main memory.

An non-volatile variable can be cached as many times as is desired in all threads.

Essentially

  • Every time you read a volatile variable it has the value of the most recent write to it from any thread.

  • Every time you read a non-volatile variable it has the value of the most recent write to it from this thread and only may have the value that other threads have written.

In the specific case that is the most common cause of issues it is quite possible for one thread to write a value to a variable and a second thread never sees the new value.