What's the best practice to ensure atomic read of a database table using JDBC?

前端 未结 6 1365
情深已故
情深已故 2021-02-19 06:26

I have an java application reading from a database table for jobs to process, and I may have multiple instances of this application running on different servers as each job is i

6条回答
  •  暖寄归人
    2021-02-19 07:11

    When using databases of a transactional nature, one popular practice is to perform ROW-LEVEL LOCKING. Row-level locks prevent multiple transactions from modifying the same row. SELECT for UPDATE is an easy way to achieve this effect. Assuming you have a processes table:

    SELECT process_id, status 
    from processes
    for UPDATE of status SKIP LOCKED;
    

    When done processing, issue

    update processes set status = 'updated'
    where process_id = :process_id;             --from before
    

    Issue

    commit;
    

    to release the lock.

    Here's an actual example

    Disclaimer: SELECT FOR UPDATE is a form of pessimistic locking and has its caveats as explained by Burleson. However, it might be a viable solution if the client is not web-based and extremely concurrent.

提交回复
热议问题