简体   繁体   中英

how can we handle concurrent transactions in hibernate

We have implemented a multi threaded application for updating a column of the table in database

ie, user account balance . The hibernate is used for interacting our application with data base. The application is deployed in multiple servers and will be worked as a cluster .

suppose the multiple requests are sent for updating the same user account in database. how can we handle this situation? The request from multiple servers or different threads from same server will try to update this at the same time. how can ensure the atomicity of the operation. can we do the same by data base -table or row- level lock using hibernate or spring framework

Example :

thread A from server S1 and thread B from server S2 access the same record R at the same time .

First the thread A from server S1 update the value of R to R1 and commit the transaction .

At the same time the thread B from server S2 update the value of R to R2 and commit the transaction .

what will be the outcome of this scenario?. we have to lock one of the transaction for the right results?. how can we lock the transaction because it is came from different servers?.

You can use Hibernate optimistic locking.

Optimistic locking assumes that multiple transactions can complete without affecting each other, and that therefore transactions can proceed without locking the data resources that they affect. Before committing, each transaction verifies that no other transaction has modified its data. If the check reveals conflicting modifications, the committing transaction rolls back[1].

More information here : https://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch05.html

For scenarios you mentioned, you need to consider below points:

  1. Setting Transaction isolation level. Refer this link for setting transaction isolation level. Most of the time, READ COMMITTED suffice the requirement, but you can explore other options as well.

  2. If you have multiple transactional resources like JMS then think of using XA Transaction. ie In your configuration you can use XA complaint DB driver. Refer this link for further details . XA drivers offers 2-phase commit protocol which maintains atomicity of transaction.

  3. If you have EJBs then container managed transaction can do all transaction related job for you. Refer this link for more .

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