【问题标题】:hibernate concurrency threading issue休眠并发线程问题
【发布时间】:2015-02-19 13:41:11
【问题描述】:

我们正在为我们的应用程序使用 spring/hibernate.. 我有一个 cron 工作可以选择 新的 cmets 来更新父子关系,其中评论可以由另一个 cmets 作为父级.. cron 分块选择 cmets.. 我的问题是假设我有 10 个 cmets.. 1,2,3...10

cron 将分块处理 cmets
线程 1 (1..5)
线程 2 (6-10)

// now in hibernate I'm using 
@PersistenceContext(name = "pu1", type = PersistenceContextType.TRANSACTION)
protected EntityManager em;

因此 thread-1 从父表中读取以检查当前 cmets 块是否有任何父表。然后它将默认值插入到父表中。

问题是线程 1 插入数据库父表的内容对线程 2 不可见,反之亦然。

// we are using,, but this is not working
commentsService.getEntityManger().flush();

// the only way to see the changes either by adding 
commentsService.getEntityManger().getTransaction().commit() // this will throw exception (transaction is not active)

// OR by adding 
Thread.sleep(3000); //before reading from parent table.

// from logs "select * from parent" for each thread.
// by this time comment 648 was inserted to parent 
2015-02-19 04:54:09,289 DEBUG [pool-2-thread-1] (CommentsServiceImpl.java:679) - Parent Table:: 23424977 for Comment 648
2015-02-19 04:54:09,289 DEBUG [pool-2-thread-1] (CommentsServiceImpl.java:679) - Parent Table:: comment_id: 648 for Comment 648

// by this time comment 649 was inserted to parent
// comment number 649 is inserted to parent table, but thread-2 can't see comment number 648 which is supposed to be available in parent table
2015-02-19 04:54:09,292 DEBUG [pool-2-thread-2] (CommentsServiceImpl.java:679) - Parent Table:: comment_id: 23424977 for Comment 649
2015-02-19 04:54:09,292 DEBUG [pool-2-thread-2] (CommentsServiceImpl.java:679) - Parent Table:: comment_id: 649 for Comment 649

【问题讨论】:

    标签: java multithreading spring hibernate concurrency


    【解决方案1】:

    如果 T1 和 T2 都处于活动状态,并且如果在任一事务中,您希望看到另一方刷新到数据库但尚未提交的更改,则需要将事务隔离级别更改为 READ_UNCOMMITTED:

    http://www.byteslounge.com/tutorials/spring-transaction-isolation-tutorial

    【讨论】:

    • 但是我正在使用 oracle.. 并且 oracle 不支持 READ_UNCOMMITTED.. 有没有其他解决方案.. 我该如何强制提交
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多