Seems like a common issue but I don’t know a straight forward answer for it-
environment
- Java EE environemnt (several JVMs)
- 2 phase commit setup
- Oracle DB
given
DB table with ‘AMOUNT’ column
logic
if SELECT SUM(AMOUNT) WHERE... + current amount < Const. ==> insert row
problem
race condition – i would like to insert the row only when i do ‘commit’. meanwhile, i dont want no other thread to access the data i used for my summation. i would also like to reduce the non accessed db data as much as possible in order not to detain other threads.
current solution
use of Oracle’s SELECT FOR UPDATE mechanism
Does anyone have other solutions for dealing with this problem? Out of the box solutions would be welcomed as well.
JPA as part of Java EE provides locking mechanisms.
In general there are pessimistic and optimistic locking.
Pessimistic locking in fact locks the table row when data is read (the resulting SQL is a
SELECT FOR UPDATE ...as your current solution), e.g.Optimistic locking uses a version column for each table:
The pessimistic approach seems most suitable for your