Search code examples
javamultithreadingspring-bootasynchronousthread-safety

Thread-safety while using @Async annotation


I am using the java @async annotation in my spring-boot application for processing and uploading excel files. It is working fine even if I am doing a multiple file upload at roughly the same time. However, I want to know if the below code that I have implemented is thread-safe or not. My understanding is that it is not and it can fail. I am unable to reproduce the concurrency issue

My Code:

while (rowIterator.hasNext()) {  
    Row row=rowIterator.next();

    if(row.getRowNum()==0) 
        continue;

    BatchScript script=new BatchScript();                       
    String rtId=row.getCell(0).toString();
    String query=row.getCell(1).toString();
    String agent=row.getCell(2).toString();
    script.setRtId(rtId);
    script.setQuery(query);
    script.setAgentName(agent);
}

In the code BatchScript is my POJO class. Can you please let me know if it will fail or not?


Solution

  • If the Rows collection is shared by multiple threads, then there is a possibility of ConcurrentModificationException. This will be the case when threads mutating your Rows list. If not there is no shared mutability in your code and so we can say that it is thread-safe.