Question

I'm maintaining a system at work and I've found a bug which can be resolved if the rest webservice methods are somehow synchronized. The system uses Jersey for rest methods and Spring framework for JDBC - I've never seen anyone use plain old java's "synchronized" method on webservices so don't know if thats even right or wrong.

Here's how the code is structured (just the superficial details) + comments inline:

@Path("/path")
@Component
public class WebService {
  @Autowired
  private ServiceImpl serviceImpl;
  ...
  @POST
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  @Path("/innerPath")
  public Response method1(@FormDataParam("id") String id) {
    ...
    /* this is where I need synchronization
     * both the verify and insert methods should execute one user at a time
     * otherwise all users will be able to insert
     */
    boolean v = serviceImpl.verify();
    if (v) {
      serviceImpl.insert(); //once insert succeeds, verify will start to fail
    }
    ...
  }
}

@Service
public class ServiceImpl {
   @Autowired
   private DaoImpl daoImpl;
   ...
   @Transactional
   public boolean verify() {
     boolean v = daoImpl.verify();
     return v
   }

   @Transactional
   public void insert() {
     daoImpl.insert();
   }
}

@Repository
public class DaoImpl {
  private JdbcTemplate jdbcTemplate;
  ...
  public boolean verify() {
    String sql = "....";
    ...
    int count = jdbcTemplate.queryForInt(sql);
    if (count > 0) {
      return false;
    }
    return true;
  }

  public void insert() {
    String sql = "....";
    ...
    jdbcTemplate.queryForInt(sql);
  }
}
Was it helpful?

Solution

I'm solving the concurrency issue by using a third dummy table where each thread will first try to insert its unique data as a record and then proceed with whatever it wants to do.

This dummy table's primary key are set of columns which map one-to-one with all the unique data a thread holds.

If concurrent threads try to insert into this dummy table then only one insert will succeed (because of primary key constraints).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top