We have a code that inserts a new value into the table column that is a primary key. First we are doing select and if this value is not present then we do insert.
query = "SELECT AValue from ATableCache WHERE AValue=" + avalue;
ResultSet rs = stmt.executeQuery(query);
if (!rs.next())
{
query = "INSERT INTO ATableCache (AValue) VALUES ('" + avalue + "')";
stmt.executeUpdate(query);
}
At race conditions this algorithm can result in an SQL error while inserting a value that was just inserted by another thread. One of the options is synchronization but this will slow execution. Please, note that insertion happens quite seldom. Is there more efficient algorithm?