Search code examples
javamongodb-javajava-threads

What is the best practise for using a service in java threads?


I'm writing an application that will launch several threads - the amount varies per execution, but in general more than 5 and less than 100 - each of which will repeatedly read from a Mongo database.

public class MyThread implements Runnable {
    private MyMongoClient myMongoClient = MyMongoClient.getInstance();

    public MyThread() {
    }

    @Override
    public void run() {
        Document myDocument = myMongoClient.getDocumentById("id");
        Document newDocument = new Document("id": "newId");
        myMongoClient.writeDocument(newDocument);
    }
}

I have an existing singleton service class to query and update Mongo, and would like any advice on patterns to follow for using it in the threads?

public class MyMongoClient {
    private static MyMongoClient INSTANCE = new MyMongoClient();
    private myCollection; 

    private MyMongoClient() {
        try (MongoClient mongoClient = new MongoClient(host)) {
            MongoDatabase db = mongoClient.getDatabase("myDatabase");
            myCollection = db.getCollection("myCollection");
        } 
    }

    public static MyMongoClient getInstance() {
        return INSTANCE;
    }

    private Document getObjectById(String id) {
        // Implementation
    }

    private write writeDocument(Document document) {
        // Implementation
    }    
}

As shown, each thread will read from existing entries, but not update any of them, and will write new entries using the same service

Should each thread use the same instance of the service, or should I rewrite the service so that each thread has its own instance?


Solution

  • You're going to get an error because you close your MongoClient in that constructor. MongoClient has a built in connection pool so there's no reason to create more than one. Create just the one and share it amongst your threads.