title: Java thread safety of list
body: <p>I have a List, which is to be used either in thread-safe context or in a non thread-safe one. Which one will it be, is impossible to determine in advance.</p>
  
  <p>In such special case, whenever the list enters non-thread-safe context, I wrap it using </p>
  
  <blockquote>
    <p>Collections.synchronizedList(...)</p>
  </blockquote>
  
  <p>But I don't want to wrap it, if doesn't enter non-thread-safe context. F.e., because list is huge and used intensively.</p>
  
  <p>I've read about Java, that its optimization policy is strict about multi-threading - if you don't synchronize your code correctly, it is not guaranteed to be executed correctly in inter-thread context - it can reorganize code significantly, providing consistency in context of only one thread (see <a href="http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.3" rel="noreferrer">http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.3</a>). F.e., </p>
  
  <blockquote>
    <p>op1;
    op2;
    op3;</p>
  </blockquote>
  
  <p>may be reorganized in </p>
  
  <blockquote>
    <p>op3;
    op2;
    op1;</p>
  </blockquote>
  
  <p>, if it produces same result (in one-thread context).</p>
  
  <p>Now I wonder, if I </p>
  
  <ol>
  <li><p>fill my list before wrapping it by synchronizedList,</p></li>
  <li><p>then wrap it up,</p></li>
  <li><p>then use by different thread</p></li>
  </ol>
  
  <p>, - is there a possibility, that different thread will see this list filled only partially or not filled at all? Might JVM postpone (1) till after (3)? Is there a correct and <strong>fast</strong> way to make (big) List being non-thread-safe to become thread-safe?</p>