Does MongoCollection.forEach require thread safety?

When using the MongoDB Java Async Driver: Do I need to use the following callback to use the AtomicInteger counter, or will the regular function be executed?

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); 
+5
source share
1 answer

The only real difference between the MongoDB Java API and its async symbol is that the methods of the latter are not blocked and accept callbacks as arguments. This means that what you get in your callback is equivalent to what the method returns in a non-asynchronous API.

Here you use the find method. It returns a β€œnormal” iterative, so calling forEach on it will not result in multiple threads.

In other words, you do not need AtomicInteger : your apply method is called sequentially on the same thread.


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

  • add System.out.println(Thread.currentThread().getName()); inside your block. You will see that it is always executed by the same thread;
  • add a breakpoint inside your block to stop only the stream. Once again, a breakpoint will block all code.
+2
source

Source: https://habr.com/ru/post/1241917/


All Articles