Discussions

EJB design: Optimistic locking pattern

  1. Optimistic locking pattern (5 messages)

    I see the optimistic locking pattern being implemented, but why is this needed.

    Surely, just using container managed transactions, works in the same way and the db will throw an exception if there is a concurrency issue? Therefore, not needing to code the addtional timestamp or version number etc. Also wouldn't we get the same action with bean manged transactions as well?

    Nick..

    Threaded Messages (5)

  2. Optimistic locking pattern[ Go to top ]

    Container managed transaction won't handle concurrency issues when working in a clustered environment. In a clustered environment it's possible to have two separate beans (transaction) working on the same set of data at the same time.

    In addition, if your working in an environment where some other application can update your datastore without your knowledge and you're using some sort of caching mechanism you need Optimistic locking so you don't over-write the changes.

    Tim
  3. Optimistic locking pattern[ Go to top ]

    Does this mean that whenever I am writing beans which update. In a multiuser environment, I should always implement this pattern?

    So much for EJB taking care of concurrency issues for me. Is this really the case, and we shouldn't rely on EJB for concurrency?
  4. Optimistic locking pattern[ Go to top ]

    Does this mean that whenever I am writing beans which update. In a multiuser environment, I should always implement this pattern?


    Not necessarily. If your running clustered application servers and want to make sure one user can not over write changes made by another user without being notified then you need to implement this pattern.

    However if you're not in a clustered environment, or you don't care if the "last update wins" then you don't need to use optomistic locking.

    >Is this really the case, and we shouldn't rely on EJB for concurrency?

    That's one of those big "it depends" questions.

    Tim
  5. Optimistic locking pattern[ Go to top ]

    Cheers
  6. Optimistic locking pattern[ Go to top ]

    Optimistic locking also allows you to have long-lived 'transactions' -- for instance you can retrieve an entity from the DB and create a web page which allows a user to edit the entity's attributes.

    When the user submits the page you can compare the version and alert the user if someone else has updated it while they were editting it.

    This is impossible to do purely with container managed transactions, although of course they are still important when a number of optimistically locked entities are updated in a single transaction.

    Tom