This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
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.
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.