简体   繁体   中英

hibernate concurrency threading issue

we are using spring/hibernate for our application.. i have a cron job which picks new comments to update the parentage relation where a comment can be parented by another comments.. the cron picks the comments in chunks.. my issue is suppose i have 10 comments.. 1,2,3...10

the cron will process comments in chunks
thread-1 (1..5)
thread-2 (6-10)

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

so thread-1 reads from parent table to check if there is any parents for the current chunk of comments.. then it inserts default values to parent table.

the issues is what thread-1 inserts into database parent table is not visible to thread-2 and vice versa.

// 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

If T1 and T2 are both active and if, in either transaction, you want to see changes flushed to the database by the other but not yet committed you will need to change the transaction isolation level to READ_UNCOMMITTED:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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