Best way to generate an incrementing ID in multithreaded environment

Hi

I have a "best practice" kind of question.

I need to insert a record in an Oracle table where primary key is an incrementing numeric ID. In order to insert a new record, first i need to figure out what the maximum ID is and then increment it.

In a multithreaded environment, this can cause an error when, let's say, there are 2 threads, and each one is simultaneously querying the table for the max ID. Each query will return the same result and hence only 1 query will succeed at inserting the new record. The second insert will cause a primary key conflict when trying to execute.

Is making the code synchronized the best solution in this situation or is there a better way?

Thanks in advance.

[737 byte] By [bgoykhmana] at [2007-11-27 4:01:27]
# 1

Hi,

using Oracle sequence could be easy and effective, just insert sequence.NEXTVAL into the particular column. Oracle should take care of possible conflicts, it should always provide different (means incremented) value.

I dont recommend using agregate function MAX(column).

Good luck,

Rgds

Miroslav

miroslav.ka at 2007-7-12 9:06:10 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...