Count
Count

Reputation: 1423

Update a table after select in multi-threaded environment

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);

Upvotes: 0

Views: 1031

Answers (1)

wero
wero

Reputation: 32980

In the UPDATE statement use the condition "WHERE id=" + rowId + " AND status = 0"

If the update count returned by Statement.executeUpdate is 0 then you know that another thread has picked that id at the same time and you can ignore it in the current thread.

Upvotes: 1

Related Questions