Only 44 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!

  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting duplicate ID  RSS feed

Ravishanker kumar
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

We are generating some unique ID for some specific object.
For this we maintain a counter for all those objects in databse. Database table is as below

1 | 1 | com.Object1
2 | 1 | com.Object2

When we need id for any object we,
1. fetch current value of counter from database[updateCount method in code],
2. increment by one in counter and update into database(to keep counter updated for next time)[ updateCount method in code]
3 return current value for counter[updateCount method in code]
4 do some manipulation in counter with date and generate unique id.[ getNIVID method in code]
The code in method updateCount() is synchronized on some static object.
Issue is, some time I get duplicate id, This must be due to duplicate Id returned by method updateCount(). I think this may be due to static lock used (Please see the code).
I am not able to figure out exact cause for this. Do I need to make it singleton class and synchronize code on that instance instead of static object, but I am not sure whether this will fix the issue.
Any help will be appreciated.
Following is the code used for the same.Please let me know in case of any clarification.

Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess that your program is running simultaneously on two or more workstations.
If yes, then your code for incrementing counter in the database is not thread safe.
You must lock a row in the table to prevent others session to retrieve old counter value until you increment it and save a new value.
You can do it for example with 'SELECT ... FOR UPDATE' sql clause - refer to your database documentation if this is implemented.
SELECT ... FOR UPDATE acquire row locks on retrieved records, locks are released on next commit operation.
You can also use an updatable ResultSet to lock the record and update it.
Matt Cartwright
Ranch Hand
Posts: 152
Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what you are looking for, and looks like trying to implement is a
Universally Unique ID (UUID).

Why not try java.util.UUID.randomUUID()?

Or make you counter an auto-increment field
in the same or one of the database tables.

If your database does not support auto-increment
field you still can do it in a stored procedure
which is triggered "on update".

Anything you can do in this regard in the database
will help you with transaction demarcation in your
code and eventually performance.

Hope that helps
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!