Platinum Partner
java,hibernate,concurrency

Handling concurrency using optimistic locking technique

In a real world scenario, we deal with concurrency mostly during a database update .To be more specific, if a specific row in database table is being processed by two concurrent threads/process one should not update the stale data. Personally, I never liked the concepts of synchronized, Lock, Wait, etc to achieve the above results. As a developer we all use some sort of Version control system (CVS stands for Concurrent version control). Its kind of pretty well known fact that versioning is the one of the best way to avoid concurrency(much better compared to even timestamps).

Most of the modern persistence frameworks like Hibernate, Ibatis, JPA, etc suppport automatic versioning at row level. A hibernate sample will look like,

< class name="foo" optimistic-lock="version" table="FOOS">
....
< version column="version" name="version" type="int">
....
< /class>

When there is a update operation on the FOOS table,

(1) Hibernate issues an update statement like

UPDATE FOOS SET BAR='bar', VERSION=2
WHERE ID=1234 AND VERSION=1

(2) Hibernate checks the JDBC row count, and throws a StaleObjectStateException if no rows were updated 


You don't have to worry much about other things. Most of the current persistence framework will automatically update/check the version number during each update. 


And moreover, the classic Synchronized,Lock,Wait,etc approach is tied to that specific JVM.If you are running a distributed application across different JVM's,you have more things to worry about..

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}