0

I'm not sure if this is the correct to handle but I have the following method below:

public void updateOrInsertRecord () {
    boolean doesRecordExist = dao.doesUsageRecordExits();

    if (doesRecordExist) {
       dao.updateRecord();
    } 
    else {
       dao.insertRecord();
    }
}

The above has the potential to cause issues if two threads finishing determining if the record exist, the method could potentially insert or update the same record twice. It was suggested that I wrap the body of the method in a synchronous block as shown below:

synchronized(this) {
    boolean doesRecordExist = dao.doesUsageRecordExits();

    if (doesRecordExist) {
       dao.updateRecord();
    } 
    else {
       dao.insertRecord();
    }
}

This does resolve the issue but this to me does not seem scalable. Is there a better way to handle a situation like this? Something that promotes scalability? Or is this the preferred/recommended method of handling a situation as such. The service is a Dropwizard(0.9.2) service using a JDBC connection for Postgresql. Any help or insight would be most appreciated. Thank you!

UPDATE: I tried using jdbi method inTransaction but still the multi thread issue persist. Code is below

public interface Dao extends Transactional<Dao> {

    @SqlQuery("SELECT EXISTS(SELECT STUFF)")
    Boolean doesRecordExists();

    @SqlCall("INSERT STUFF")
    void insertRecord();

    @SqlUpdate("UPDATE STUFF")
    void updateRecord();
 }

public void updateOrInsertRecord () {
    dao.inTransaction((transactional, status) -> {

         boolean doesRecordExist = dao.doesRecordExits();

        if (doesRecordExist) {
           dao.updateRecord();
        } 
        else {
           dao.insertRecord();
        }

        return null;
    })
}
Joseph Freeman
  • 1,644
  • 4
  • 24
  • 43
  • 1
    Use a database transaction. You’re right to be suspicious of using synchronized here, it’s a bad idea. – Nathan Hughes Jun 07 '18 at 02:07
  • Thanks for confirming my suspicion! I'm too familiar java side db transactions. Could elaborate a bit more or point me to an example? – Joseph Freeman Jun 07 '18 at 13:11
  • you can use transactions by calling commit on the jdbc connection. i know nothing about dropwizard so can't recommend anything specific. i have explanations of synchronzied vs transactions at https://stackoverflow.com/a/43420462/217324 or https://stackoverflow.com/a/43420462/217324 – Nathan Hughes Jun 07 '18 at 21:00

0 Answers0