1

I have a tomcat server running my web application. In order to follow the mongo documentation, I need to figure out how my server can always refer to the same instance of MongoClient.

My idea is to create a class variable using the static identifier called

public static mongoClient;

When my server starts, I would call a method like MongoClass.start() which would make the class variable:

public static void start() {
    mongoClient = new MongoClient("localhost", "port");
}

This would allow myself a connection to my database throughout the application. Each time an HTTP request is being handled using javax and jersey, I would make an instance of the MongoClass and do some stuff. Because at the beginning, I initialized the mongoclient variable, any new class initiated will already have this connection to the database.

When the server shuts down, I would call the method MongoClass.close() which does:

public static void close() {
    mongoClient.close()
}

This would close the thread, effectively handling memory leak issues. In particular the error:

The web application [/app] appears to have started a thread named 
[MongoCleaner1953449629] but has failed to stop it. This is very likely to 
create a memory leak.

Is my reasoning correct here? Is this a good way to handle the MongoDB java driver?

user145570
  • 201
  • 1
  • 2
  • 7

0 Answers0