Reputation: 508
I have this Rest API to getGroupId which will increment the counter, and return the group id when we call this getGroupId. But it is returning the duplicate sequence number when I'm making concurrent calls. Can anyone help me how to handle this concurrent API requests.
@RequestMapping(value = "/groupid/get/{dbindex}/{dc}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Object getGroupId(@PathVariable Integer dbindex, @PathVariable Object dc) {
service.setDB(dbindex);
if (service.get("groupid", dc) == null) {
BigInteger groupid = new BigInteger("1");
service.set("groupid", dc, groupid);
return service.get("groupid", dc);
} else {
BigInteger groupid = new BigInteger(String.valueOf(service.get("groupid", dc)));
BigInteger updated = groupid.add(new BigInteger("1"));
service.set("groupid", dc, updated);
return service.get("groupid", dc);
}
}
Upvotes: 1
Views: 4204
Reputation: 77
The simplest way to solve this is to add the synchronized
keyword to the getGroupId method declaration. It will prevent multiple threads from executing the method at the same time.
It may not be the best way to solve it, however. If a synchronized method is called by multiple threads concurrently, they will have to take their turns, one at a time. If it's expected that the method will be called with high concurrency it could be a performance issue.
Better solutions may be available but they would require changes that go beyond the scope of the code you have shown. If the only code you can change is in this method, you have to synchronize it to make your code thread safe.
Upvotes: 2