gpt4 book ai didi

hibernate - JPA 悲观锁尝试永远不会超时

转载 作者:行者123 更新时间:2023-11-29 11:24:13 25 4
gpt4 key购买 nike

我正在尝试在 JPA 中使用悲观锁定,通过 Hibernate 3 针对 Postgres 数据库。我无法让锁超时 - 它似乎永远挂起。

这是一个例子:

EntityManagerFactory factory; 

// (initialise the factory )

EntityManager em1 = factory.createEntityManager();
EntityManager em2 = factory.createEntityManager();

// em1 gets a lock

EntityTransaction transaction1 = em1.getTransaction();
transaction1.begin();
MyObject object1 = em1.find( MyObject.class, 1, LockModeType.PESSIMISTIC_READ );

// em2 tries for a lock

Map<String,Object> timeoutProperties = new HashMap<String,Object>();
timeoutProperties.put("javax.persistence.lock.timeout", 5000);

EntityTransaction transaction2 = em2.getTransaction();
transaction2.begin();
MyObject object2 = em2.find( MyObject.class, 1, LockModeType.PESSIMISTIC_READ, timeoutProperties );

// After five seconds I expect em2 to bail out, but it never does.

transaction1.rollback();
transaction2.rollback();

据我了解,em2 应该尝试最多五秒 (5000ms) 来获取锁,然后应该抛出异常。相反,代码会陷入僵局。

如果我在两个不同的线程中运行它,那么我会看到线程 2(带有 em2)在线程 1 (em1) 释放它后立即获得锁。所以锁定正在发生,只是永远不会超时。

我使用 PESSIMISTIC_WRITE 和任何超时值(2ms、0ms 'NO WAIT')等得到相同的效果。

我使用的是 Hibernate 3.6.10 Final(最新的 Hibernate 3 版本)和 Postgres jdbc 驱动程序 9.2-1003.jdbc4(最新的驱动程序)。我正在针对 Postgres 8.4 数据库运行。

我找到的所有文档都表明这应该有效。有什么想法吗?

谢谢,阿拉斯泰尔

最佳答案

Postgres SELECT for update 语法只提供了如果不能立即获得锁则不等待的选项。请参阅 postgres 文档。

To prevent the operation from waiting for other transactions to commit, use the NOWAIT option. With NOWAIT, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately. Note that NOWAIT applies only to the row-level lock(s) — the required ROW SHARE table-level lock is still taken in the ordinary way (see Chapter 13). You can use LOCK with the NOWAIT option first, if you need to acquire the table-level lock without waiting.

当使用 postgres 时,我观察到任何超过 0 的超时值都会导致 hibernate 发出 SELECT FOR UPDATE 但是当超时为 0 时它会发出 SELECT FOR UPDATE NO WAIT

关于hibernate - JPA 悲观锁尝试永远不会超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19266015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com