Monday, July 11, 2011

Entity Object Locking

Object locking is required to avoid concurrency problem in an application. Generally speaking, there are two types of object locking: Pessimistic Locking and Optimistic Locking.

Pessimistic locking is a locking strategy where we prevent users from doing certain things. Here is an example of pessimistic locking:

User A performs update action on an entity object, then user A gets write lock on the being updated entity object. At almost concurrent time, user B performs update action on the same entity object, then user B's action is rejected since the entity object's write lock is being hold by user A.

JPA doesn't support this strategy because it has many disadvantages. It can make the application slower because certain action have to wait for entity object's lock to be released.

Optimistic locking is a locking strategy where we will use object comparison to decide whether a certain transaction will be committed or rolled back. Here is an example of optimistic locking:

When a user performs update action on an entity object, he/she will retrieve a copy of that entity object. Changes are made to the copy object, not the original. When the user is about to save it to database, application checks whether data have been updated since the user retrieved it. If no update has been made, the user gets entity object's write lock, then the data is committed. Otherwise, it is rejected.

JPA support this strategy. It is implemented by adding a column to the table for the entity to save a version number. Every time the row is updated, the version number is incremented. It is by comparing that version number the update action is committed or rejected.

0 comments:

 

©2009 Stay the Same | by TNB