How do I ensure data consistency in this concurrent situation?

Posted by MalcomTucker on Stack Overflow See other posts from Stack Overflow or by MalcomTucker
Published on 2010-03-12T13:09:56Z Indexed on 2010/03/12 13:17 UTC
Read the original article Hit count: 186

The problem is this:

  • I have multiple competing threads (100+) that need to access one database table
  • Each thread will pass a String name - where that name exists in the table, the database should return the id for the row, where the name doesn't already exist, the name should be inserted and the id returned.
  • There can only ever be one instance of name in the database - ie. name must be unique

How do I ensure that thread one doesn't insert name1 at the same time as thread two also tries to insert name1? In other words, how do I guarantee the uniqueness of name in a concurrent environment? This also needs to be as efficient as possible - this has the potential to be a serious bottleneck.

I am using MySQL and Java.

Thanks

© Stack Overflow or respective owner

Related posts about concurrency

Related posts about data-consistency