简体   繁体   English

在Java EE环境中测试乐观锁定

[英]Testing Optimistic Locking in Java EE environment

As I understand if a row in a database table is updated simultaneously by multiple threads the database would flag an error. 据我了解,如果数据库表中的行被多个线程同时更新,则数据库将标记错误。

In our production environment we have 2 Tomcat servers in a cluster. 在生产环境中,集群中有2台Tomcat服务器。 It might happen that the two users are directed to each one of the Tomcat servers at the same time and they update the same record in the database table. 这两个用户可能同时被定向到每台Tomcat服务器,并且他们更新数据库表中的同一条记录。 As a result, an exception would be thrown. 结果,将引发异常。

How do I simulate this situation on my local machine? 如何在本地计算机上模拟这种情况? Or how would I do it some environment which is same as production? 还是在与生产相同的环境中如何处理?

Technology that I am working on: Java 6, Spring 3, Hibernate, MS SQL Server 2008 and Tomcat 7. 我正在研究的技术:Java 6,Spring 3,Hibernate,MS SQL Server 2008和Tomcat 7。

As I understand if a row in a database table is updated simultaneously by multiple threads the database would flag an error. 据我了解,如果数据库表中的行被多个线程同时更新,则数据库将标记错误。

Not necessarily. 不必要。 If you run two statements like these below, 如果您运行以下两条这样的语句,

UPDATE foo SET bar=baz WHERE bah=doh;

database could simply schedule to run these queries one after another. 数据库可以简单地安排一个又一个地运行这些查询。 But there are plenty of possibilities for a deadlock and, generally speaking, result depends on your queries and their timing, data set, etc. 僵局很多可能性 ,通常来说,结果取决于查询及其查询的时间,数据集等。

You wan't to simulate the scenario. 您将无法模拟场景。 I read it as you want to test the code which handles optimistic lock exception. 当您要测试处理乐观锁异常的代码时,我已阅读它。 I would simply simulate the class which throws exception and explicitly throw OptimisticLockException. 我将简单地模拟抛出异常并显式抛出OptimisticLockException的类。 Use the simulated class inside exception handler in test environment and write a test fr exception handler. 在测试环境中的异常处理程序中使用模拟的类,并编写一个测试fr异常处理程序。

I believe you are not worried about testing whether optimistic lock is working or not. 我相信您不必担心测试乐观锁是否起作用。 As it is the job of Hibernate developers. 因为这是Hibernate开发人员的工作。

You can simulate it by using two transactions. 您可以使用两个事务来模拟它。 Start the first tx. 开始第一个发送。 Start the second tx. 启动第二个发送。 Make some changes in the first TX and commit it. 在第一个TX中进行一些更改并提交。 Make some changes in the second TX and commit it. 在第二个TX中进行一些更改并提交。 Hibernate should give you the OptimisticLockException. Hibernate应该给您OptimisticLockException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM