Search code examples
javaspring-bootpessimistic-locking

Is it possible to "lock" and "unlock" a pessimistic lock in two different methods in Spring Boot?


I am currently having the need of using pessimistic lock in my vending machine project. When more than 1 person is choosing their products, I would like to use the pessimistic lock to prevent both people from selecting the same product. My project is Java, Spring Boot.

Is it possible for me to execute the "lock" of the pessimistic lock in one method call and somehow "unlock" the pessimistic lock in another method call? (The "lock" process is executed when the user confirms the product, and the "unlock" process is executed when the user either pays for the products or desire to re-choose the products.) Or are there any better solutions to this problem?


Solution

  • The Lock API allows one method to acquire a lock and another method to release it.

    A particular implementation of Lock could allow one thread to acquire a lock and another on release it. But ReentrantLock doesn't. The javadocs for each Lock implementation should document this aspect.


    However, I think you should not be modelling this using Java language locks at all; either primitive object locks or Lock. These are designed to provide mutual exclusion for certain blocks of code, and thereby to control access and update to a shared data structure.

    I think you should be modelling this as "holds" or "reservations" used as follows:

    • The user acquires hold when they select the product
    • A hold is released when:
      • the user buys the product
      • the user cancels the transaction
      • the user takes too long to complete the transaction
      • the user ... walks away

    So a hold might consist of:

    • a hold id
    • a product identifier
    • a product quantity
    • a user id or a session id
    • an expiry timestamp

    It will be easiest to implement if the "holds" are stored in your database.

    You just need to maintain the invariant that the number of holds for a product is less or equal to the number of unsold items of that product.

    Finally, you will need something to automatically release holds that have reached their expiry. And something to deal with the case where a user attempts to purchase an item after their hold has expired.