Do database transactions prevent race conditions?

前端 未结 4 1903
失恋的感觉
失恋的感觉 2020-11-28 04:52

It\'s not entirely clear to me what transactions in database systems do. I know they can be used to rollback a list of updates completely (e.g. deduct money on one account a

4条回答
  •  孤城傲影
    2020-11-28 05:19

    The database tier supports atomicity of transactions to varying degrees, called isolation levels. Check the documentation of your database management system for the isolation levels supported, and their trade-offs. The strongest isolation level, Serializable, requires transactions to execute as if they were executed one by one. This is typically implemented by using exclusive locks in the database. This can be cause deadlocks, which the database management system detects and fixes by rolling back some involved transactions. This approach is often referred to as pessimistic locking.

    Many object-relational mappers (including JPA providers) also support optimistic locking, where update conflicts are not prevented in the database, but detected in the application tier, which then rolls back the transaction. If you have optimistic locking enabled, a typical execution of your example code would emit the following sql queries:

    select id, version, credits from user where id = 123;  
    

    Let's say this returns (123, 13, 100).

    update user set version = 14, credit = 110 where id = 123 and version = 13;
    

    The database tells us how many rows where updated. If it was one, there was no conflicting update. If it was zero, a conflicting update occurred, and the JPA provider will do

    rollback;
    

    and throw an exception so application code can handle the failed transaction, for instance by retrying.

    Summary: With either approach, your statement can be made safe from race conditions.

提交回复
热议问题