Note that there are some explanatory texts on larger screens.

plurals
  1. PODo I need to use volatile, if 2 different write and read thread will never alive at the same time
    primarykey
    data
    text
    <p>By referring to <a href="http://www.javamex.com/tutorials/synchronization_volatile.shtml" rel="nofollow">http://www.javamex.com/tutorials/synchronization_volatile.shtml</a>, I am not sure whether I need to use <code>volatile</code> keyword in the following case, <strong>due to additional rule 3.</strong></p> <ol> <li>A primitive static variable will be write by Thread A.</li> <li>The same primitive static variable will be read by Thread B.</li> <li>Thread B will only run, after Thread A is "dead". ("dead" means, the last statement of Thread A's void run is finished)</li> </ol> <p>Will the new value written by Thread A, will always committed to main memory, after it "dead"? If yes, does it mean I need not <code>volatile</code> keyword if the above 3 conditions are meet?</p> <p>I am doubt that <code>volatile</code> is being required in this case. As it is required, then <a href="http://www.google.com/codesearch/p?hl=en#lM3pwaU8RUc/src/share/classes/java/util/ArrayList.java&amp;q=ArrayList&amp;sa=N&amp;cd=2&amp;ct=rc" rel="nofollow">ArrayList</a> may broken. As one thread may perform insert and update <code>size</code> member variable. Later, another thread (not-concurrently) may read the <code>ArrayList</code>'s <code>size</code>. If you look at <code>ArrayList</code> source code, <code>size</code> is not being declared as volatile.</p> <p>In JavaDoc of <code>ArrayList</code>, then only mention that <code>ArrayList</code> is not safe to be used for <em>multiple threads access an ArrayList instance concurrently</em>, but not for <em>multiple threads access an ArrayList instance at different timing</em>.</p> <p>Let me use the following code to issulate this problem</p> <pre><code>public static void main(String[] args) throws InterruptedException { // Create and start the thread final ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;(); Thread writeThread = new Thread(new Runnable() { public void run() { list.add("hello"); } }); writeThread.join(); Thread readThread = new Thread(new Runnable() { public void run() { // Does it guarantee that list.size will always return 1, as this list // is manipulated by different thread? // Take note that, within implementation of ArrayList, member // variable size is not marked as volatile. assert(1 == list.size()); } }); readThread.join(); } </code></pre>
    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.
 

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