Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>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.</p> </blockquote> <p>That is incorrect. Volatile fields are instance or class (static) variables and are stored in the heap.</p> <p>They <em>might</em> 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.</p> <blockquote> <p>If so, then what happen if the volatile variable is an object reference and not a primitive literal?</p> </blockquote> <p>Nothing special. Your assumptions are incorrect. Volatile variables are not stored on the stack.</p> <blockquote> <p>I know each thread has his own stack memory where it stores its own primitive literals &amp; objects references.</p> </blockquote> <p>What is stored on the thread's stack is:</p> <ul> <li>the method's local variables,</li> <li>the method's parameters,</li> <li>the method's return address etc so that the CPU knows where to go when the call returns, and (possibly)</li> <li>state of local objects that the JIT compiler has figured don't need to be stored in the heap.</li> </ul> <p>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 ...)</p> <blockquote> <p>Second, could you please explain in details using an example how the volatile keyword works and when we are supposed to use it?</p> </blockquote> <p>Check the comments, and the related questions ... or Google "java volatile example". An explanation would be redundant.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload