I have to write a code which involves making a web service call to a backend asynchronously and returning a toll free number in round robin from a list of TFNs to the caller. Below is my code
@Stateless
public class TollFreeServiceBean {
@EJB
private AsyncBackendService asyncBean;
public long getTollFreeNumber(Request request) {
//Validate request
asyncBean.callBackend(request);
return TFNUtil.getNext();
}
}
@Stateless
public class AsyncBackendService {
@Asynchronous
public void callBackend(Request request) {
// Call web service and inform a caller with `Request` is going to call
}
}
public class TFNUtil {
private static int index = 0;
private TFNUtil(){}
public static synchronized long getNext() {
// Get TFN list from cache
if(tfnList.size() >= index) {
index = 0;
}
long tfn = tfnList.get(index);
index++;
return tfn;
}
}
The idea is that the customers will get a different TFN each until the TFNs in the cache are completed. Once completed, the next customer should get the first TFN again. For example if there are 10 TFNs and 11 customers, 11th customer should receive 1st TFN. 12th customer should receive 2nd TFN and so on.
The backend system is complaining that two different simultaneous customers are landing on the same TFN. So I think my TFNUtil.getNext() logic is not right.
Can anyone please point out the bug here?