user2924127
user2924127

Reputation: 6232

Program terminates before Mongodb async query completes

I am following the tutorial: http://mongodb.github.io/mongo-java-driver/3.2/driver-async/reference/crud/. I am simply trying to connect to the database and to read a collection I have created with 2 documents inside:

import com.mongodb.async.SingleResultCallback;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
import com.mongodb.async.client.MongoCollection;
import com.mongodb.async.client.MongoDatabase;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;

public class Main {

    MongoClient client = MongoClients.create();
    MongoDatabase database = client.getDatabase("mydb");

    public Main() {
        readUsers();
    }


    public void readUsers() {

        MongoCollection<Document> collection = database.getCollection("user");

        // find documents
        collection.find().into(new ArrayList<Document>(),
                new SingleResultCallback<List<Document>>() {
            @Override
            public void onResult(final List<Document> result, final Throwable t) {
                System.out.println("Found Documents: #" + result.size());
            }
        });
    }

    public static void main(String[] args) throws Exception {
        new Main();
    }

}

But I keep getting the following error:

Dec 28, 2015 6:22:51 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Dec 28, 2015 6:22:51 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out

I am not sure why this is happening? I am following what the documentation is showing.

Upvotes: 2

Views: 3391

Answers (1)

David Soroko
David Soroko

Reputation: 9116

You need to make sure that your Main() code doesn't complete before readUsers has returned something like:

...
import java.util.concurrent.Semaphore;

public class Main {
    MongoClient client = MongoClients.create();
    MongoDatabase database = client.getDatabase("mydb");
    Semaphore semaphore = new Semaphore(0);

    public Main() throws Exception {
        readUsers();
        semaphore.acquire();
    }


    public void readUsers() {

        MongoCollection<Document> collection = database.getCollection("users");

        // find documents
        collection.find().into(new ArrayList<Document>(),
                new SingleResultCallback<List<Document>>() {
                    @Override
                    public void onResult(final List<Document> result, final Throwable t) {
                        System.out.println("Found Documents: #" + result.size());
                        semaphore.release();
                    }
                });
    }

    public static void main(String[] args) throws Exception {
        new Main();
    }

}

Upvotes: 1

Related Questions