You are viewing a plain text version of this content. The canonical link for it is here.
Posted to derby-user@db.apache.org by Amir Michail <am...@gmail.com> on 2007/01/09 19:16:30 UTC
handling race conditions
Hi,
I was wondering how one should handle race conditions.
My problem has to do with generating ids. I suppose that generating
ids using derby's auto generation does not result in any problems with
respect to race conditions.
However, in my case, I use a pair of items (x, y) where y starts
counting at 1 for each x. So you can have a race condition where both
threads see the same value of y and end up computing the same
subsequent id of y+1.
How is something like this normally handled in derby db so as to
maximize concurrency?
I'm using manual transactions btw.
Amir
RE: handling race conditions
Posted by de...@segel.com.
> -----Original Message-----
> From: Amir Michail [mailto:amichail@gmail.com]
> Sent: Tuesday, January 09, 2007 12:17 PM
> To: Derby Discussion
> Subject: handling race conditions
>
> Hi,
>
> I was wondering how one should handle race conditions.
>
> My problem has to do with generating ids. I suppose that generating
> ids using derby's auto generation does not result in any problems with
> respect to race conditions.
>
> However, in my case, I use a pair of items (x, y) where y starts
> counting at 1 for each x. So you can have a race condition where both
> threads see the same value of y and end up computing the same
> subsequent id of y+1.
>
> How is something like this normally handled in derby db so as to
> maximize concurrency?
>
> I'm using manual transactions btw.
>
> Amir
[mjs] There are a couple of ways that you can do this.
Option 1:
Create a table foo with two columns x,y;
There will only be one row in the table.
When you need to get a value of either x or y, you lock the table, fetch the
row, and update the counter (x or y);
The downside is that it may hurt performance if you've got a lot of threads
running at the same time all waiting on the lock.
Option 2:
You didn't specify if all of the threads are part of the same app.
You can then create a pair of static variables at the class level and then
have a private method that does the updates and a public method that does
the fetch id request. Then in either the public or private method, you could
set up a mutex lock so that other threads will wait in a queue until you are
done.