Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>Would this be guaranteed to print "done"?</p> </blockquote> <p>As said in <a href="http://rads.stackoverflow.com/amzn/click/0321349601">Java Concurrency in Practice</a>:<br></p> <blockquote> <p>When thread <code>A</code> writes to a <code>volatile</code> variable and subsequently thread <code>B</code> reads that same variable, <strong>the values of all variables that were visible to A prior to writing to the <code>volatile</code> variable become visible to B after reading the <code>volatile</code> variable</strong>.</p> </blockquote> <p>So <strong>YES</strong>, This guarantees to print "done".</p> <blockquote> <p>What would happen if instead of declaring b as volatile I put the write and read into a synchronized block?</p> </blockquote> <p>This too will guarantee the same.<br></p> <blockquote> <p>Don't use volatile to protect more than one piece of shared state.</p> <p>Why?</p> </blockquote> <p>Because, volatile guarantees only Visibility. It does'nt guarantee atomicity. If We have two volatile writes in a method which is being accessed by a thread <code>A</code> and another thread <code>B</code> is accessing those volatile variables , then while thread <code>A</code> is executing the method it might be possible that thread <code>A</code> will be preempted by thread <code>B</code> in the middle of operations(e.g. after first volatile write but before second volatile write by the thread <code>A</code>). So to guarantee the atomicity of operation <code>synchronization</code> is the most feasible way out.</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. 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