Dhruv Pant
Dhruv Pant

Reputation: 3

Java Preventing concurrent access to a method in Spring MVC

I want to add some dummy data in a table using Spring MVC.

Here is the code:-

In Dao

    public int generateData(){
    int iData = 80001;
    String qry = "SELECT p FROM TestDomain p";
    List<TestDomain> runQry = daoHelper.findByQuery(qry);
    if(runQry.size()!=0){
        TestDomain tdom = runQry.get((runQry.size()-1));
        iData = tdom.getNum_data();
        iData++;
    }


    return iData;
}

This generates a dummy value to be added to an integer column in the table. Basically if the table is empty it generates 80001 or if not then increment the existing maximum value. Kindly note that I cannot make the column unique because of some requirement constraint. After I get the data from the above function, I just insert it in the table using the merge function.

 entityManager.merge(entity);

Now the problem is that when multiple users hit the generate function at the same time, they are assigned the same data and this causes duplicacy when the data is pushed to the table by different clients. How do I prevent this duplicacy?

Edit..

1, I have already tried the java synchronized keyword on my generate method and it doesn't work, maybe because I'm using the spring's transactional in my service layer.

2, I cannot use database sequence to generate unique data, the data has to come from the generate method.

Upvotes: 0

Views: 646

Answers (2)

Shervin Asgari
Shervin Asgari

Reputation: 24509

Have a look at the @Version annotation in hibernate. It might solve your problem.

Or, what you can do is using pessimistic locking and locking your table when performing operations.

Upvotes: 1

Anudeep Gade
Anudeep Gade

Reputation: 1395

Its not the problem of Spring MVC data duplicacy issue. Your application needs to prevent the data duplicacy by controlling concurrent access to the method which is generating id's (or) preferred way is to use a database sequence to get the next id instead of application generating the id.

If you can't use a database sequence and still want to use generate method then your application need to control the concurrency either by adding JAVA synchronized keyword to generate method (and/or) lock any object to allow single thread access to the method. This will make other users/threads to wait until this method is executed.

Upvotes: 1

Related Questions