java-从多个线程中选择和更新行的安全方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-从多个线程中选择和更新行的安全方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2334字,纯文字阅读大概需要4分钟。
内容图文
![java-从多个线程中选择和更新行的安全方法](/upload/InfoBanner/zyjiaocheng/687/2cdcbf9783d941cb9f1194066cd2a7d1.jpg)
表拍卖:AuctionType(整数),Auctioned(Json /文本).
我需要一种从多线程拍卖中拍卖的方法.
例:
机器1:
int id = 1;
Object obj = parse("SELECT Auctioned FROM Auction WHERE AuctionId = "+id+";");
obj = edit(obj);
update("UPDATE Auction SET Auctioned = "+obj.toString()+" WHERE AuctionId="+id+";");
机器2:
update("UPDATE Auction SET Auctioned = <value> WHERE AuctionID=<value2>");
问题是,如果:
Thread1获取Sql列.
Thread2更新Sql Column.
Thread1使用过期的获取结果来更新Sql Column,因为结果Thread2更新被覆盖.
因此,我想找到一种防止数据丢失的安全方法,例如:
Thread1 fetchs Sql Column & stores checksum.
Thread2 updates Sql Column.
Thread1 updates Sql Column if checksum equals storedChecksum.
我希望校验和检查在sql引擎端而不是在过程中完成.
但是为此,我将需要一种方法来允许SQL更新查询在数据库引擎中自行取消,并在不满足校验和条件的情况下返回结果.
解决方法:
有一种通用的RDBMS机制可以满足此要求,称为SELECT … FOR UPDATE.
原理是,在选择该行时,您指示您的RDBMS即将更新,并且应该锁定它.如果在释放锁之前另一个SQL会话尝试访问(读取,更新)数据,则将其置于等待状态.
大多数RDBMS都实现此功能.通常的约束是您需要使用数据库事务来使其正常工作(即,禁用自动提交).提交(或回滚)拥有的事务时,将释放该锁.
随着MySQL InnoDB:
SELECT ... FOR UPDATE
: For index records the search encounters, locks the rows and any associated index entries, the same as if you issued an UPDATE statement for those rows. Other transactions are blocked from updating those rows, from doing SELECT … FOR SHARE, or from reading the data in certain transaction isolation levels.
SELECT Auctioned FROM Auction WHERE AuctionId = ? FOR UPDATE;
在Oracle中:FOR UPDATE clause.
The
FOR UPDATE
clause lets you lock the selected rows so that other users cannot lock or update the rows until you end your transaction.
SELECT Auctioned FROM Auction WHERE AuctionId = ? FOR UPDATE OF Auctioned;
SQL Server有点不同,您需要使用the UPDLOCK hint:
Specifies that update locks are to be taken and held until the transaction completes.
SELECT Auctioned FROM Auction WITH (UPDLOCK) WHERE AuctionId = ?;
FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. […] That is, other transactions that attempt UPDATE, DELETE, SELECT FOR UPDATE […] of these rows will be blocked until the current transaction ends.
SELECT Auctioned FROM Auction WHERE AuctionId = ? FOR UPDATE;
内容总结
以上是互联网集市为您收集整理的java-从多个线程中选择和更新行的安全方法全部内容,希望文章能够帮你解决java-从多个线程中选择和更新行的安全方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。