I have a singleton spring service that is being called by spring rest controller.
The singleton service MyService
has some method addRecordIfNotExistsBefore
, which has the following implementation:
public void addRecordIfNotExistsBefore(String record){
boolean isExist = checkIfRecordNotExitsBefore();
if (!isExist){
addRecordToDb(record);
}
}
The problem is - as appears - when two clients request the same service at the same time, then the record being added twice to the database.
I can apply the double-check idiom in some simple implementation like:
public void addRecordIfNotExistsBefore(String record){
boolean isExist = checkIfRecordNotExitsBefore();
if (!isExist){
synchoronized(this){
isExist = checkIfRecordNotExitsBefore();
if (!isExist){
addRecordToDb(record);
}
}
}
}
Does it valid solution, or is there another better solution?