title: Optimistic Locking by concrete (Java) example
body: <p>I have spent my morning reading all the top articles that <a href="https://www.google.com/#q=optimistic+locking">Google churns up on optimistic locking</a>, and for the life of me, I still don't really get it.</p>
  
  <p>I <em>understand</em> that optimistic locking involves the addition of a column for tracking the record's "version", and that this column can be a timestamp, a counter, or any other version-tracking construct. But I'm still not understanding how that ensures WRITE integrity (meaning that if multiple process are updating the same entity at the same time, that afterwards, the entity correctly reflects the true state it should be in).</p>
  
  <p>Can someone provide a <strong>concrete, easy-to-understand</strong> example of how optimistic locking could be used in Java (against, perhaps, a MySQL DB). Let's say we have a <code>Person</code> entity:</p>
  
  <pre><code>public class Person {
      private String firstName;
      private String lastName;
      private int age;
      private Color favoriteColor;
  }
  </code></pre>
  
  <p>And that <code>Person</code> instances get persisted to a <code>people</code> MySQL table:</p>
  
  <pre><code>CREATE TABLE people (
      person_id PRIMARY KEY AUTO_INCREMENT,
      first_name VARCHAR(100) NOT NULL,
      last_name VARCHAR(100) NOT NULL,        # } I realize these column defs are not valid but this is just pseudo-code
      age INT NOT NULL,
      color_id FOREIGN KEY (colors) NOT NULL  # Say we also have a colors table and people has a 1:1 relationship with it
  );
  </code></pre>
  
  <p>Now let's say there are 2 software systems, or 1 system with 2 threads on it, that are trying to update the same <code>Person</code> entity at the same time:</p>
  
  <ul>
  <li>Software/Thread #1 is trying to persist a surname change (from "<em>John Smith</em>" to "<em>John Doe</em>")</li>
  <li>Software/Thread #2 is trying to persist a change in the favorite color (from <em>RED</em> to <em>GREEN</em>)</li>
  </ul>
  
  <h3>My questions:</h3>
  
  <ol>
  <li>How could optimistic locking be implemented on the <code>people</code> and/or <code>colors</code> tables? (Looking for specific DDL example)</li>
  <li>How could you then utilize this optimistic locking at the application/Java layer? (Looking for specific code example)</li>
  <li>Can someone run me through a scenario where the DDL/code changes (from #1 and #2 above) would come into play in my scenario (or any other scenario) and would "optimistically lock" the <code>people</code>/<code>colors</code> tables correctly? Basically, I'm looking to see optimistic locking in action, with an easy-to-follow explanation of why it works.</li>
  </ol>