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.