title: Threadsafe bidirectional association in Java
body: <p>What is a good way to implement thread-safe bidirectional associations? Is there maybe a good library or code generator?</p>
  
  <p>Here is a non thread-safe example:</p>
  
  <pre><code>class Foo {
  
      private Foo other;
  
      public Foo getOther() {
          return other;
      }
  
      public void setOther(Foo other) {
          this.setOtherSecretly(other);
          other.setotherSecretly(this);
      }
  
      void setOtherSecretly(Foo other) {
          if (this.other != null) this.other.other = null;
          this.other = other;
      }
  }
  </code></pre>
  
  <p>My requirements for thread-safety are:</p>
  
  <ul>
  <li>No deadlocks</li>
  <li>Eventual consistency (When all threads stop modifying the objects, a consistent state is eventually reached. I.e., it is acceptable that <code>assert foo.getOther().getOther() == foo</code> fails when another thread is performing <code>setOther</code> concurrently.</li>
  <li>Sequential behaviour. If a thread performs <code>setOther</code> and no other other thread overrides the value, <code>getOther</code> immediately returns the new value for that thread.</li>
  <li>No traveling back in time. Once a thread observed a new value with <code>getOther</code>, it will never again receive the old value (unless it is set again).</li>
  </ul>
  
  <p>Also nice to have:</p>
  
  <ul>
  <li>Low contention, especially no global lock. The solution should scale well.</li>
  <li>As little synchronization overhead as possible. It should have reasonable performance for a single thread.</li>
  <li>Low memory overhead. When an object has 5 associations, I don't want 3 additional fields per association. Local variables in setters are ok.</li>
  </ul>
  
  <p>My application will have 16 threads working on about 5.000 objects of several classes.</p>
  
  <p>I couldn't come up with a solution yet (no, this is not homework), so any input (ideas, articles, code) is welcome.</p>