title: volatile in java with long, int, boolean, and many different cases of write
body: <p>I have an exam coming up in a concurrent programming class.  The class is fairly well structured, but I feel I must not understand the "volatile" keyword as well as I thought.  I have read through other posts on how it works, and it seems to make sense, but my understanding of Java as a whole is limiting me.  These are practice questions T/F, would anyone mind answering them and explaining why they are True or false?  I have put my best guesses and explanations in</p>
  
  <p>a. <strong><em>_</em>__</strong>_An int variable count is shared among several threads, 
  where the only actions on count are to read its value, and to increment it. 
  It suffices to mark count as volatile.</p>
  
  <p>false, volatile keyword ensures that there are no local caches of this variable, but a race condition can still occur because the new value depends on the previous for count(and the operation is therefore not atomic), so two threads can read the value, increment it and there is still a race condition on write back.  If count was not dependent on previous value (such as just an ID number that is written) this would work.</p>
  
  <p>b. <strong><em>_</em>___</strong> The long variable count is shared among several threads, 
  where the only actions on count it are to read its value, and to increment 
  it. It suffices to mark count as volatile. </p>
  
  <p>same as above, except even if the value is not dependent on previous values, this is not thread safe, since it is NEVER an atomic operation because long takes two write cycles for the upper and lower 32 bit writes and reads </p>
  
  <p>c. <strong><em>_</em>___</strong> The boolean variable b, initially false, is shared between 
  multiple threads. One specific thread sets its value to true, the other 
  threads read the value. It suffices to mark b as volatile. </p>
  
  <p>true, changing the boolean is atomic and can occur before an interrupt occurs, and updates for all other threads.</p>
  
  <p>d. <strong><em>_</em>___</strong> The boolean variable b is shared between multiple threads. 
  Any thread can set or read its value. Once b is set to true, it remains true 
  henceforth. It suffices to mark b as volatile.</p>
  
  <p>true, same reason as above.</p>
  
  <p>Thanks so much!</p>