[英]Update a table after select in multi-threaded environment
I am using a SQL table for state maintenance of my application. 我正在使用SQL表维护应用程序的状态。
Initially I was extracting new keys from my table using a select query and then updating there status as 'picked up' 最初,我是从我的表使用select查询提取新的密钥,然后更新存在状态为“拿起”
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 我认为有可能是一个SQL只有解决我的问题太多,但安装的Java代码
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);
In the UPDATE statement use the condition "WHERE id=" + rowId + " AND status = 0"
在UPDATE语句中,使用条件"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. 如果Statement.executeUpdate
返回的更新计数为0,则您知道另一个线程同时选择了该ID,并且可以在当前线程中忽略它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.