title: Memory barriers and coding style over a Java VM
body: <p>Suppose I have a static complex object that gets periodically updated by a pool of threads, and read more or less continually in a long-running thread. The object itself is always immutable and reflects the most recent state of something.</p>
  
  <pre><code>class Foo() { int a, b; }
  static Foo theFoo;
  void updateFoo(int newA, int newB) {
    f = new Foo();
    f.a = newA;
    f.b = newB;
    // HERE
    theFoo = f;
  }
  void readFoo() {
    Foo f = theFoo;
    // use f...
  }
  </code></pre>
  
  <p>I do not care in the least whether my reader sees the old or the new Foo, however I need to see a fully initialized object. IIUC, The Java spec says that without a memory barrier in HERE, I may see an object with f.b initialized but f.a not yet committed to memory. My program is a real-world program that will sooner or later commit stuff to memory, so I don't need to actually commit the new value of theFoo to memory right away (though it wouldn't hurt).</p>
  
  <p>What do you think is the most readable way to implement the memory barrier ? I am willing to pay a little performance price for the sake of readability if need be. I think I can just synchronize the assignment to Foo and that would work, but I'm not sure it's very obvious to someone reading the code why I do that. I could also synchronize the whole initialization of the new Foo, but that would introduce more locking that actually needed.</p>
  
  <p>How would you write it so that it's as readable as possible ?<br>
  Bonus kudos for a Scala version :)</p>