aspose file tools
The moose likes Java in General and the fly likes Concurrent Users inserting a record Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Concurrent Users inserting a record" Watch "Concurrent Users inserting a record" New topic
Author

Concurrent Users inserting a record

Sahil Sharma
Ranch Hand

Joined: Aug 27, 2003
Posts: 152
Hi,

I am facing a problem when two user are simultaneously trying to insert a record in a table and both of them getting the same id. I am generating the id (pattern xxx-xxx) in my DAO layer and the way I am doing this is - first I am retrieving the last id created and incrementing it by one to generate a new id and then inserting the records in the database with that new id and calling a commit.

How should I then handle this situation so that no two user end up having the same id.

Thanks
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35237
    
    7
Most databases allow the key to be generated by the DB (using an auto-increment sequence); that will ensure that they are unique.

If the ID needs to be generated in the application code, then that code needs to be made thread-safe (maybe by synchronizing it).


Android appsImageJ pluginsJava web charts
Sahil Sharma
Ranch Hand

Joined: Aug 27, 2003
Posts: 152
thanks for the reply Ulf.
Unfortunately I cannot use the database incremantor due the requirements, which are forcing me to handle the incrementing logic in application code. This ID is sort of a ticketID.

The only worry I have with respect to using the synchronization is - how much will it impact the performance of the application as I am inserting records in more than 10 tables after generating the ID.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35237
    
    7
In that case, only the code that increments the ID needs to be synchronized, not the full DB logic that subsequently makes use of that ID, right? (I'm assuming that it's not important to re-use an ID in case of a DB rollback.)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

Since Java 5.0 you can use an AtomicLong for this:


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Concurrent Users inserting a record
 
Similar Threads
Transactions and Threading
I want to log sessionid and date time when new session starts
how to retrieve the new ID of the auto_increment column
duplicate records
Save Or Update In Hibernate Always Updating