Async vs Sync Java driver

771 views
Skip to first unread message

Ernesto Reig

unread,
Oct 20, 2015, 6:47:34 AM10/20/15
to mongodb-user

I´m quite confused about java drivers for Mongodb. Reading the official documentation it seems that you can use the normal MondoDB Driver or the MongoDB Async Driver.

The first question is: Can I use both in the same application or I have to choose one?


Trying to use the Async driver I found things that I used to do (with the normal driver) in which I get a bit lost now. For example, I used to do this:

FindIterable<Document> iterable = db.getCollection("my_coll").find(query);
String json = JSON.serialize(iterable);


And now I really don´t know how to do since they have not included the JSON class from the Async driver.

Second question: If I cannot use both drivers at the same time, how can I then serialize a FindIterable<Document>?


Thank you very much in advance

Ross Lawley

unread,
Oct 20, 2015, 10:54:50 AM10/20/15
to mongodb-user
Hi Ernesto,

You are correct in that a new separate Async driver was released in 3.0, along side the synchronous one.

1) Can I use both in the same application or I have to choose one?

In theory, yes you can use both side by side. However it would pose challenges as they API and naming conventions are mirrored, making for conflicting and each driver has its own connection pool.  So in practise its better and simpler to choose a specific driver that meets your needs.

2) If I cannot use both drivers at the same time, how can I then serialize a FindIterable<Document>?

In 3.0 there were many changes and older parts of the API (such as DB and DBCollection) have been deprecated.  The idea is that users will be able to slowly migrate their code from the old API into the new.  However, I appreciate it can be a source of confusion as to which classes to use.  Happily there is an example of serializing to Json in the  documentation hub.  Using that strategy you should be able to serialise documents into a Json array string.

I hope that helps,

Ross

Ernesto Reig

unread,
Oct 20, 2015, 11:19:27 AM10/20/15
to mongodb-user
Thank you very much for the answer Ross.
Now I am wondering if using the Async driver is convenient at all in a webapp where you query mongodb in your java back-end and throw the results to the javascript front-end. Would this make sense since you have to wait for the results to return from mongodb before sending the response to the front-end?
I would have to do something like
collection.find().forEach(...
and gather all the results in a set/list before throwing them to the front-end. Therefore this would be the same as using the sync driver right?

Kind regards,
Ernesto

Ross Lawley

unread,
Oct 20, 2015, 2:43:22 PM10/20/15
to mongodb-user
Hi Ernesto,

The question, is the Async driver right for you? really depends on your stack and your comfort levels with async frameworks. Traditionally, when you execute something synchronously, you wait for it to finish before moving on to another task. When you execute something asynchronously, you can move on to another task before the previous may have finished.  In general this allows better utilising of resources and would work well with an event driven application server.  

Either way, nothing is sent to the user until you have all the data you require.  This is simple in the sync driver as the code is chronological, but in the async driver the callback has to handle the logic.  Multiple callbacks can often become painful and complicated to read with heavy nesting.  For that reason we released the rxJava driver, which uses Observers to make callbacks composable and the logic easier to reason.

The API's for the Sync and Async drivers are deliberately kept the same, so the same logic can be applied to both.  Below is an example of collecting all the Json versions of documents into a Json Array using Java 8:

String documentsAsJson = collection.find().map(Document::toJson)
.into(new ArrayList<>())
.stream()
.collect(Collectors.joining(", ", "[", "]"));

I hope that helps,

Ross

Ernesto Reig

unread,
Oct 21, 2015, 5:53:30 AM10/21/15
to mongodb-user
Ok, I am now finally getting to understand the Async driver. So the way to work with it would be something like this?:

public String getDocuments(){
  ...
  collection.find(query).map(Document::toJson)
        .into(new HashSet<String>(), new SingleResultCallback<HashSet<String>>() {
            @Override
            public void onResult(HashSet<String> strings, Throwable throwable) {
              // HERE I HAVE TO GET THE ALL DATA IN THE SET
              // AND MAKE IT TO A JSON STRING
              // AFTER THAT I WOULD WAKE THE MAIN THREAD
            }
        });
// HERE I HAVE TO PUT THE MAIN THREAD TO WAIT UNTIL I HAVE THE DATA IN THE onResult()
// SO I CAN RETURN THE DATA BACK TO THE FRONT-END
  return jsonString;
}

Is this assumption right?
Reply all
Reply to author
Forward
0 new messages