I recently established load balancing using apache 2.4 +mod_jk 1.2.37 +tomcat 6 environment.
Everything working perfectly but I am having a scenario where a unique sequential no has to generate based on some conditions.
But after deploying the application in all 3 (clusters) tomcats, my application starts generating duplicates.
My coding is as follows, as 3 clusters is getting 3 requests at a time all threads are acting at a same time on the same Db and each and every thread picks and same next No (using getDocSeriesNo() )and increment it by 1 so at an instance of time 3 threads getting the same no for example 100 then all 3 threads +1 all threads getting 101 i.e duplicates i.e blunder for our application because that unique no is key for each and every transaction and after that all 3 threads are increment the unique no reference table by 1 (using updateDocSeries())
How can I fix this using a coding logic in a clustered environment ???
by the way used I used session replication using delta manager and my pojo is lazy loading in jpa 2.1.
public String createDoc() {
try {
if (cgpass.getDocStatus().equalsIgnoreCase("DRAFT")) {
synchronized (CargoGatePassAction.class) {
Long a=0l;
IptDocumentseries ids = dochelper.getDocSeriesNo(param1,param2,param3,param4);
if(null!=idseries)
nextno= idseries.getNextNo();
if(nextno!=0l)
cgpass.setDocNum(nextno);
}
if (checkApprovers(username)) {
cgpass.setDocStatus("Waiting for approval");
if (cgpass.getId() != null) {
getModel().setModifiedBy(
SecurityContextHolder.getContext()
.getAuthentication().getName());
iicgpd.update(cgpass);
} else {
getModel().setModifiedBy(
SecurityContextHolder.getContext()
.getAuthentication().getName());
iicgpd.save(cgpass);
}
for (IptCargoParameterConfig vanCP : cParamList) {
vanCP.setDocNum(cgpass.getDocNum());
vanCP.setDocSeriesCode(cgpass.getDocSeriesCode());
cParamDAO.update(vanCP);
}
dochelper.updateDocSeries();
}
}
}
catch (OptimisticLockException ole) {
cgpass.setDocSeriesCode(null);
cgpass.setDocNum(null);
setDocseries(null);
setDcno(cgpass.getDraftNum());
addActionMessage(OLEM);
return SUCCESS;
}
return SUCCESS;
}
public synchronized void updateDocSeries(String param1,String param2,String param3,String param4)
{
Long nextno= 0L;
List<IptDocumentseries> idslist =iidsd.findByDocSeriesCode(param1,param2,param3,param4);
try{
if(idslist!=null && !idslist.isEmpty())
{
nextno = idslist.get(0).getNextNo();
IptDocumentseries ids = new IptDocumentseries();
ids = idslist.get(0);
ids.setNextNo(++nextno);
ids.setModifiedDate(getCurrentTimeStamp());
iidsd.update(ids);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
<pre><pre lang="java">