-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Avoid data race on “counter” field (with cluster)
PostPosted: Wed Jul 29, 2009 1:51 am 
Newbie

Joined: Tue May 06, 2008 4:19 am
Posts: 6
Hi guys,

I have an entity, let's say it's Coupon, each time the coupon is used I need to increase the useCount field, when it reaches 100, the coupon cannot be used or updated anymore. See the mapping config below
Code:
   <class name="Coupon" table="COUPON">
        .......
        <property name="useCount" type="long" column="USE_COUNT"></property>
        .......
    </class>

In native SQL, I can easily use the SQL below with database underlying lock
Code:
update coupon set use_count=use_count+1 where id=? and use_count < 100

If two transactions tries to update the same row, the latter one will be blocked until the first one commits or rolls back. Let's say the use_count is 0 initially, if T1 and T2 tries to update the same row, when T1 updates the row, T2 will be blocked, if T1 commits, T2 sees use_count as 1, and will update it to 2. If T1 rolls back, T2 sees use_count as 0 and will update it to 1.
However, in Hibernate, you need to load the row into memory as a POJO and increase the useCount property by Java code
Code:

coupon.setUseCount(coupon.getUseCount()+1);
session.flush();//helps a little, but not solve totally
.....
session.update(coupon);

This will not use the database underlying lock to lock the row so T1 and T2 probably sees the same snapshot and updates the use_count from 0 to 1 twice.
How can we avoid this kind of data race with database lock? I am running a cluster of application servers so synchronization in java does not help. I need it at the database layer.

Thanks,
Daniel


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.