[JAVA-2111] Synchronization mechanism for Java Async Driver Created: 09/Feb/16  Updated: 11/Sep/19  Resolved: 17/May/16

Status: Closed
Project: Java Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Minor - P4
Reporter: Abbass Marouni Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

I'm using the 3.2.1 Async driver to do the following :

...
 
while(InputIterator.hasNext()){
 
   MongoCollection.insertOne(document, new SingleResultCallback<Void>(){
    @Override
    public void onResult(Void v, Throwable t) {
        
    }
});
 
}
...
 
MongoClient.close();

The only issue is that MongoClient is being closed before all of the queued inserts are processed and I'm getting "Pool is closed". I cannot use CountDownLatch as I don't know the size of my InputIterator.

Does the Async driver provide any synchronization mechanisms that we can use in this case ?



 Comments   
Comment by Ross Lawley [ 09/Feb/16 ]

Hi amarouni,

Thanks for the ticket just to note for future as this is a usage question its better suited to the mongodb-user mailinglist or stackoverflow as you will reach a boarder audience there. We often find questions there are more discoverable for future users and help the community as a whole.

Unfortunately, there isn't a mechanism as you describe, which would be akin to using some sort of "CountUpLatch" and then counting up on each callback and then latch.await(N) on the latch outside the loop. One way to stop a race condition would be to have a CountDownLatch(1) and then chain the inserts (losing parallelism) and in the last elements callback count down the latch. Doing that in the async driver can be cumbersome and it would be simpler using the RxJava driver as the Observable abstraction is much higher level than callbacks. To improve performance I would also recommending buffering the results and using collection.insertMany - this would reduce the number of network round trips but it would still require chaining to remove any race conditions.

I hope that helps,

Ross

Generated at Thu Feb 08 08:56:21 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.