I am trying to update an entity called StaticsModel in a MongoDb database. This entity has properties such as mapped (int), date (DATE), sent (int) ,id (primary key) etc. I am updating the same entity for a particular date in different API-s , for instance in one API I update the number of sent, in one other API I update the number of mapped etc. Is the following code threadsafe ? Because when several PC-s hit several API-s at the same time I get different results for the same date. For instance when I update the number of mapped ,the number of sent gets another random variable. How can I make this code threadsafe? I presumed that setting the properties as atomic would solve the issue but I am having doubts now. Thanks
StatisticsModel statisticsModel = new Statistics();
String today = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
statisticsModel.setDate(today);
List<StatisticsModel > statisticsCreate = statisticsRepository.findByDate(today);
if (statisticsCreate .size() < 1)
atomicLong.set(0);
for (StatisticsModel statisticsModelRes : statisticsCreate ) {
statisticsModel.setMapped(statisticsModelRes.getMapped());
statisticsModel.setSent(statisticsModelRes.getSent());
}
statisticsModel.setReceived(atomicLong.incrementAndGet());
statisticsRepository.upsert(statisticsModel );
Edit: I think my problem is almost similar to this one:
It's not possible to lock a mongodb document. What if I need to?