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.
source share