Write Conflict how it actually works

I read that write conflict occurs when MongoDB detects that the document has been modified by another operation since it was last read. So I wrote the following code to see if it throws the write conflict or not

public void test() throws InterruptedException {
        Thread t1 = new Thread(()->{
            try {
                processor.performTransaction(LIVE,0);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread t2 = new Thread(()->{
            try {
                MDC.put(OrgMongoDBFactory.SHARD_KEY, "1");
                processor.performTransaction(COMPLETED,10000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Data d1 = DataFixture.getData();
        d1.setRoll(0l);
        d1.setName("jm1");
        d1.setAge(0);
        d1.save(journeyMetaVersion);
        t1.start();
        t2.start();
        Thread.sleep(80000);
        List<Data> versions = dataDao.findAll();
        log.info("the version is: {}", versions);
    }

Inside Processor following method is there

public void performTransaction(Data.dataStatus status,int waitTime) throws InterruptedException {
        Data d1 = Data.findByRollNameAndAge(0l,"jm1",0);
        Thread.sleep(waitTime);
        log.info("got data as: {}", d1);
        d1.setStatus(status);
        Data d2 = DataDao.save(d1);
        log.info("the data is: {}", d2);
        Thread.sleep(waitTime);
        log.info("completed waiting");
    }

Here two threads are created which read from the Data collection and fetches the value. After that thread2 goes to sleep and thread1 goes ahead and updates the value. Now once the sleeptime is over for thread2 it tries to update the value. So here the update call should fail based on the above definition of Write conflict as post the last read there changes to the document.
But when I run the following code it doesn’t give any error
Please explain the possible reason for the above

Hi @Nishant_Kumar4,

Here are a couple of other posts in the forum that can help maybe:

Now back to your issue: in your code, I don’t see you use the API for transactions.

Without a transaction, there is no reason for a write conflict as all the operations would then be considered atomic (and transactional on their own).

I hope this helps.
Cheers,
Maxime.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.