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);
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:
System.out.println(Thread.currentThread().getName());
inside your block. You will see it is always performed by the same thread;If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With