Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does MongoCollection.forEach need to be thread safe?

When using the MongoDB Async Java Driver: Does the following callback need to use a AtomicInteger counter or would a normal int do the job?

Block<Document> theBlock = new Block<Document>() {
  AtomicInteger counter = new AtomicInteger();
  @Override
   public void apply(final Document document) {
     counter.incrementAndGet();
   }
 };
SingleResultCallback<Void> callbackWhenFinished = ...

collection.find().forEach(theBlock, callbackWhenFinished);
like image 853
jack Avatar asked Oct 19 '22 16:10

jack


1 Answers

The only real difference between the MongoDB Java API and its async counterpart is that the methods of the latter are non-blocking and take callbacks as arguments. This means that what you receive in your callback is equivalent to what the method returns in the non-async API.

Here, you use the find method. It returns a "normal" iterable, so calling forEach on it will not result in multiple threads.

In other words, you don't need an AtomicInteger: your apply method is called sequentially, by the same thread.


If you still have doubts or need a "proof", you can do one of the following:

  1. add a System.out.println(Thread.currentThread().getName()); inside your block. You will see it is always performed by the same thread;
  2. add a breakpoint inside your block, configured to stop only the thread. Once again, the breakpoint will block the whole code.
like image 59
Derlin Avatar answered Oct 21 '22 22:10

Derlin