java - Thread safety while access Db in spring bean -


i have singleton spring service being called spring rest controller.

the singleton service myservice has method addrecordifnotexistsbefore, has following implementation:

public void addrecordifnotexistsbefore(string record){      boolean isexist = checkifrecordnotexitsbefore();      if (!isexist){         addrecordtodb(record);     } } 

the problem - appears - when 2 clients request same service @ same time, record being added twice database.

i can apply double-check idiom in simple implementation like:

public void addrecordifnotexistsbefore(string record){      boolean isexist = checkifrecordnotexitsbefore();      if (!isexist){         synchoronized(this){              isexist = checkifrecordnotexitsbefore();             if (!isexist){                 addrecordtodb(record);             }         }     } } 

does valid solution, or there better solution?

i think solution have database constraint check uniqueness of record in database scene application deployed in multiable nodes


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -