List<String> Codes= req.getCodes();
List<String> existingCodes = helper.getExistingCodes(Codes);
Codes.removeAll(existingCodes);
for (String Code : Codes)
{
addCode(Code);
}
I am getting a request containing different codes to be inserted in DB in "Codes" list, but meanwhile I have to check no duplication so I am getting the existing codes from DB in "existing codes" and then just removed the duplication and add new codes in DB with function addCode(), now the problem is when multiple threads will access this
I m passing the same code for each thread.
Thread 1 got an existing code null and moved towards adding a new code but before that thread 2 comes and again gets existing codes which are again null and it will be a move to add the same code again and here the problem comes.
I have written the "merge into" query for adding a code but it isn't working any other solution without using synchronized in java???
Copyright Notice:Content Author:「H. Shahan」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/47156465/avoid-race-condition-in-accessing-db-data-without-synchronized-in-java