Yugesh
Yugesh

Reputation: 4092

How to prevent array cleared from @Async Method argument in Spring Boot?

I am experiencing some sort of thread issue with the @Async method annotation. Am processing data from csv to DB, for every 10000 record pass these records to another method annotated with @Async. After calling the @Async method immediately clear the list in main method, it clear in @Async also. Please help to handle this issue.

Main Method in One Class

@Async("threadPoolTaskExecutor")
@Override
public CommonResponse generateDedupInputFile(String inputRequest){

   if (stagingData.size() == 10000) {

            futures.add(databaseUpdateChanges.addInputDataStagingV12("tbl_staging", fieldQuery,
                    config.getInputFields(), batchId, stagingData));

            logger.info("staging size: {}", stagingData.size());
            
            stagingData.clear();

        }

}

DB Class

@Async("threadPoolTaskExecutor")
@Transactional
public Future<String> addInputDataStagingV12(String tableName, String fieldQuery, List<InputField> inputFields,
        BigInteger batchId, List<StagingDataModel> stagingDataModels) {

    logger.info("Size : {}", stagingDataModels.size()); //Get data size as Zero
    /** Data insert query**/   

}

After calling stagingData.clear(); it cleared the data in addInputDataStagingV12 method also, so not able to insert data. If I removed the @Async("threadPoolTaskExecutor") working fine.

Upvotes: 0

Views: 59

Answers (1)

atish.s
atish.s

Reputation: 1903

stagingData looks to be a local variable in the class, hence anyone can update it at any time. It is best to make a copy of the list and pass it as argument to the function.

Something like this should fix the issue.

List<StagingDataModel> newStagingData = new Arraylist<>(stagingData);

futures.add(databaseUpdateChanges.addInputDataStagingV12("tbl_staging", fieldQuery,
                    config.getInputFields(), batchId, newStagingData));

Upvotes: 1

Related Questions