0

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?

Muhammad Hewedy
  • 29,102
  • 44
  • 127
  • 219
  • 1
    That is why there are different database propagation levels. Try `SERIALIZABLE` and then with your initial implementation. Also if you really want to fix it I would suggest adding a unique constraint somewhere as if it is the same record and it is only allowed once you should also have a unique constraint somewhere. – M. Deinum Jun 04 '15 at 06:14
  • I tried @Transactional(isolation=Isolation.SERIALIZABLE) on the service method but still not work! – Muhammad Hewedy Jun 04 '15 at 11:02
  • Are your transactions working? – M. Deinum Jun 04 '15 at 11:11

1 Answers1

2

I think the only solution is to have database constraint to check uniqueness of record in database scene your application is deployed in multiable nodes

Rashad Saif
  • 1,379
  • 10
  • 16