How to update row of a table in mysql maintaining consistency of data.
For Example :
Algo :
do{
CreditBalance credit = getCreditBalance(initialDeductionCreditRequest.getUserId(),
creditMetadata.getId());
if (credit.getBalance() >= cost) {
final Integer newBalance = credit.getBalance() - cost;
credit.setNewBalance(newBalance);
rowsUpdated = compareAndSetBalanceForUser(credit.getBalance(), newBalance,
credit.getUserId(), balanceCredit.getCreditId());
}
}while (rowsUpdated == 0);
-- getCreditBalance contains Query which retrieves user balance based on i/p criteria
public Integer compareAndSetBalanceForUser(Integer oldBalance, Integer newBalance, String userId,
Integer creditId) {
Session session = sessionFactoryCoreServices.getCurrentSession();
Query query = session.createQuery(
"**update CreditBalance cb set cb.balance = :newBalance , modified_date = NOW() where cb.balance = :oldBalance and cb.userId = :userId and cb.creditId = :creditId**");
query.setParameter("newBalance", newBalance);
query.setParameter("oldBalance", oldBalance);
query.setParameter("userId", userId);
query.setParameter("creditId", creditId);
return query.executeUpdate();
}
I have a use case where i need to update balance of particular user, maintaining credit balance consistent.
i run my code with 20 threads concurrently the above code is not promising data consistency.
i even tried SELECT FOR UPDATE approach which is also not promising data consistency.
is there any other way which can assure data consistency after certain set of concurrent operations.