Efficient implementation of exclusive execution
Posted
by
n0weak
on Stack Overflow
See other posts from Stack Overflow
or by n0weak
Published on 2010-12-26T12:41:59Z
Indexed on
2010/12/26
13:54 UTC
Read the original article
Hit count: 116
java
|multithreading
I have an ObjectManager class that is used to process payments. It is wrapped over the Order entities, so new instance has to be created when processing is required. I need to prevent the situation when several ObjectManager instances are dealing with the same order simultaneously (it happend once because of some errors on the remote payment processing center, somehow they called our callback urls twice). I'd love to get an advice how to implement it more efficiently.
For now, I am thinking about something like that:
public class OrderManager{
private static final CopyOnWriteArrayList<Integer> LOCKER =
new CopyOnWriteArrayList<Integer>();
private static synchronized boolean tryLock(Integer key) {
return LOCKER.addIfAbsent(key);
}
private static void releaseLock(Integer key) {
LOCKER.remove(key);
}
public void processPayment(Integer orderId) throws Exception{
if (!tryLock(orderId)) {
return;
}
try {
//operate
} finally {
releaseLock(orderId);
}
}
//remainder omitted
}
© Stack Overflow or respective owner