aspose file tools*
The moose likes Threads and Synchronization and the fly likes Getting duplicate ID Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Getting duplicate ID" Watch "Getting duplicate ID" New topic
Author

Getting duplicate ID

Ravishanker kumar
Ranch Hand

Joined: Jul 20, 2006
Posts: 53
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

IDENTIFIER | COUNTER | OBJECT
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

Joined: Jun 21, 2008
Posts: 423
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

Joined: Aug 25, 2008
Posts: 149

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
Matt
 
wood burning stoves
 
subject: Getting duplicate ID