I have spent my morning reading all the top articles that Google churns up on optimistic locking, and for the life of me, I still don't really get it.
I understand 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).
Can someone provide a concrete, easy-to-understand example of how optimistic locking could be used in Java (against, perhaps, a MySQL DB). Let's say we have a Person
entity:
public class Person {
private String firstName;
private String lastName;
private int age;
private Color favoriteColor;
}
And that Person
instances get persisted to a people
MySQL table:
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
);
Now let's say there are 2 software systems, or 1 system with 2 threads on it, that are trying to update the same Person
entity at the same time:
- Software/Thread #1 is trying to persist a surname change (from "John Smith" to "John Doe")
- Software/Thread #2 is trying to persist a change in the favorite color (from RED to GREEN)
My questions:
- How could optimistic locking be implemented on the
people
and/orcolors
tables? (Looking for specific DDL example) - How could you then utilize this optimistic locking at the application/Java layer? (Looking for specific code example)
- 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
people
/colors
tables correctly? Basically, I'm looking to see optimistic locking in action, with an easy-to-follow explanation of why it works.