Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Handling concurrency using optimistic locking technique

DZone's Guide to

Handling concurrency using optimistic locking technique

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

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..

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}