views:

36

answers:

2

Lets say I have a large number of threads inserting into a mysql database using Java.sql. After i perform an insert i would like to know the primary key of the record i just inserted. I could use getRow() on the ResultSet returned by the insert query. However, is this thread safe? Or should I fire off another select statement to find the primary key of the record I just inserted?

A: 

I don't think getRow() should be correct. getId() would be my choice, because the row ID may not be the same as the generated primary key.

I don't believe that any implementation in java.sql is thread-safe; Connection certainly is not.

Be sure to make your INSERT in a transaction context.

You need to pay attention to your isolation level. Check the javadocs for java.sql.Connection if you don't know what that means.

duffymo
+3  A: 

ResultSet does not advertise on the javadoc as being thread safe, so assume it is NOT. If you have 10 threads inserting, and somehow they get the SAME result set.. something weird will happen (or at least not guarantee to be right).

However, if you have 10 threads each doing their OWN inserting, and each one has it's own ResultSet .. you are fine. Remember, thread safety often has to do with sharing of the same OBJECT, not just the same class. ArrayList is NOT thread safe, but if you have 10 different threads with 10 different ArrayList's, you are fine. Same here with ResultSet.

bwawok