【发布时间】:2016-03-24 02:47:22
【问题描述】:
请对以下问题提供一些建议: 我有一个唯一代码列表。该代码只能使用一次,因此每个代码都有一个相关的状态(已使用/未使用)。
我担心争用/竞争条件,如果多个线程会尝试获取下一个未使用的代码。
使用 SQL 数据库(在我的例子中是 MySQL)实现它的最佳方法是什么?
第一个选项是使用锁定和读提交隔离级别:
start transaction in read-committed isolation level
select code from code_table where status = 'not-used' for update
update code_table set status = 'used' where code = :code
commit transaction
在线程争用的情况下,我相信“数据库线程”会偶然发现锁定的行,除非行写锁被释放,否则会等待,会看到(因为读提交隔离级别)这代码记录已被使用并移至其他代码记录。
第二种选择是使用类似于hibernate乐观锁的东西(我们不使用hibernate),下面是步骤说明:
start transaction in default isolation level ( read-repeatable )
select code from code_table where status = 'not-used'
commit transaction
start transaction in default isolation level ( read-repeatable )
update code_table set status = 'used' where code = :code
commit transaction
在 Java 代码中,我将检查更新了多少记录。如果更新了一条记录,一切正常,如果更新了 0 条记录 - 我重复该步骤..在第 3 次(或第 5 次)试用后 - 抛出异常。
任何帮助/建议将不胜感激。 提前谢谢你
【问题讨论】:
-
好的,删除 sql-server....