Skip to content
Advertisement

Volatile Keyword & the thread local memory [closed]

I got confused understanding the usage of the volatile keyword in Java. I have read many articles on the internet but am still getting nowhere. There are many questions in my head that I would like to ask:

First of all, Wikipedia and many blogs say that all volatile variables are stored in a Thread-Local memory over the main memory shared by all threads! I’m a little bit confused, are they meaning the stack memory? I know each thread has his own stack memory where it stores its own primitive literals & objects references.

If so, then what happen if the volatile variable is an object reference and not a primitive literal? I guess all the objects are stored in the heap space and not in the stack memory.

Second, could you please explain in details using an example how the volatile keyword works and when we are supposed to use it?

Advertisement

Answer

First of all, Wikipedia and many blogs say that all volatile variables are stored in a Thread-Local memory over the main memory shared by all threads.

That is incorrect. Volatile fields are instance or class (static) variables and are stored in the heap.

They might be referring to cache memory that is specific to a single processor / core … but that is a hardware-specific thing. But this is definitely not “thread-local”. That term means something entirely different.

If so, then what happen if the volatile variable is an object reference and not a primitive literal?

Nothing special. Your assumptions are incorrect.

Volatile variables are not stored on the stack. Indeed, if you attempt to use the volatile keyword for a local variable, you will get a compilation error. (It would make no sense. Variables on the stack are only visible to one thread. Volatile semantics are about variables that are shared by different threads.)

I know each thread has his own stack memory where it stores its own primitive literals & objects references.

What is stored on the thread’s stack is:

  • the method’s local variables,
  • the method’s parameters,
  • the method’s return address etc so that the CPU knows where to go when the call returns, and (possibly)
  • state of local objects that the JIT compiler has figured don’t need to be stored in the heap.

A method’s primitive literals are typically embedded in the code itself. String literals are elsewhere too. (When those literals are assigned to local variables they will be held on the stack …)

Second, could you please explain in details using an example how the volatile keyword works and when we are supposed to use it?

Check the comments, and the related questions … or Google “java volatile example”. An explanation would be redundant.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement