I am using a SQL table for state maintenance of my application.
Initially I was extracting new keys from my table using a select query and then updating there status as 'picked up'
I am now moving to a multi-threaded environment. the problem in multi threaded environment is that same key is extracted multiple times. System state become inconstant. I have tried using synchronized but its not work. I believe there might be a SQL only solution to my problem too, but attaching java code
Below is my code
sql ="select "+idField+",id from `tableName` where finish_time is NULL and status = 0 order by init_time limit 1"; Statement statement; statement = connection.createStatement(); synchronized (this) { ResultSet rs = statement.executeQuery(sql); if (rs.next()) { bId = rs.getString(1); rowId = rs.getString(2); } sql1 = "UPDATE `tableName` SET `pick_up_time`=Now(),`status`=1 WHERE `id`=" + rowId; executeQuery(sql1);