Hibernate version:2.1
My system creates threads that each of them would:
read table Sequence for nextId, increment the id and save back to Sequence
save the new record into Orders with the read id
shortened code:
Code:
public synchronized void syncOrder(Orders o) {
try {
Collection c;
beginTransaction();
try {
Sequence s;
List l = session.createCriteria(Sequence.class)
.add(Expression.eq("type", "ORD"))
.list();
// read old values
// update this rec
Sequence s = (Sequence) l.iterator().next();
int newId = s.getCurId().intValue();
s.setCurId(new Integer(newId + 1));
session.flush();
}
o.setId(s.getId());
} finally {
}
session.save(o);
logger.info(id + " saved Order " + o.getId() + " at " + o.getModifiedOn() + " as " + o.getStatus());
endTransaction(true);
} catch (Exception e) {
logger.error(id + ":" + o.getId() + "(" + o.getReferenceNo() + ") caused " + e);
}
}
The method containing the critical section has been synchronized and it seems only 1 thread enters at any time.
However, the log shows that threads got old values of Sequence, which has been updated by other theads, thus generating duplicated id for Orders...
I've tried flushing the session at various points, re-beginning the transaction, passing 1 session to all threads... but no luck
how can I deal with it?