Re: Optimistic Locking

Sebastien Bigaret <[email protected]> 23 Jun 2004 19:29:35 +0200
Newsgroups gmane.comp.python.modeling
Message-ID <[email protected]>
Ernesto Revilla <[email protected]> wrote:
> Dear Sébastien,
> 
> could you explain in some words, and with one example how Optimistic Locking
> should work?

Yes ;)

> 
> I saw your commits, but I thought optimistic locking would protect
> automatically the whole object from being updated from another
> computer. What does it mean an attribute is used for optimistic locking?
> That the attribute is checked that it is not updated by another person or
> that it is used to check if another person has changed the object?

Say you have obj O (a person) w/ attributes name, age and birthday.

'name' and 'age' are made 'usedForLocking', birthday isn't.

In a EC you fetch a person 'p', manipulate/update it, changing whatever
attributes, than you save changes. At this point (at saveChanges()
time), we make sure that the corresponding row has the same value for
columns 'name' and 'age' (which are marked as 'usedForLocking') than the
value it had *when the object was fetched*.

  If values are the same, the updates succeeds, otherwise saveChanges()
  fails.

That's the core of it. Optimistic locking is called optimistic because
it makes the assumptions that few conflicts will occur, so the checking
is only made at the last moment --when saving.

Now two remarks:

- if the corresponding person's birthday has been changed in the db by
  an external process, optimistic locking wont notice because the
  attribute wasn't used for locking,

- within a single *process*, two ECs will never conflict. This is not
  directly related to the way optimistic locking works, rather to the
  way the framework handles those updates. When an EC saves its changes,
  it broadcasts them to others. Default behaviour will be: when an ec
  receives an update for an object, it applies these updates, then
  applies back the changes that were made before within this ec.

  Example:
    # NB: p1=p2=Person(name='Cleese', age=42, birthday=None)
    p1=ec1.fetch(...)
    p2=ec2.fetch(...)  # p1, p2 correspond to the same rows
    
    p1.name='John Cleese'
    p1.age=24
    
    p2.age=12
    
    ec1.saveChanges()
    # now p2.name=='John Cleese', and p2.age==12

  Of course you'll have delegates at hand to implement your own
  behaviour to handle these cases.

Hopefully this makes things clearer. If not, yell at me ;)


-- Sébastien.



-------------------------------------------------------
This SF.Net email sponsored by Black Hat Briefings & Training.
Attend Black Hat Briefings & Training, Las Vegas July 24-29 - 
digital self defense, top technical experts, no vendor pitches, 
unmatched networking opportunities. Visit www.blackhat.com