Gamal Hassan
Gamal Hassan

Reputation: 41

MongoDB connection instantly closes - Java

I am using the mongodb-driver-sync-4.1.0-rc0 dependency and whenever I connect to the database I can use it within the same method but as soon as i store it as a static var and try accessing it from another class it says "state should be: open". My connection instantly closes after establishing a connection.

public static void initializeClient(){
        String uri = "mongodb+srv://myusername:[email protected]/izzi?retryWrites=true&w=majority";

        try ( MongoClient mongoClient = MongoClients.create(uri)) {

            client = mongoClient;
            izzi = client.getDatabase("izzi").getCollection("userStats");

            System.out.println(getOverallLikes());
            System.out.println(getWinnersLastMonth());
            //after this it closes the connection

        }
    }

I get this message when it disconnects: [main] INFO org.mongodb.driver.connection - Closed connection [connectionId{localValue:4, serverValue:14654}] to userstats-shard-00-02.9vs4b.mongodb.net:27017 because the pool has been closed.

Upvotes: 2

Views: 4029

Answers (2)

aran
aran

Reputation: 11900

Its behaviour is the normal one; This is a try-with-resources:

try ( MongoClient mongoClient = MongoClients.create(uri)) 
{
       client = mongoClient;
       izzi = client.getDatabase("izzi").getCollection("userStats");
       System.out.println(getOverallLikes());
       System.out.println(getWinnersLastMonth());
       //after this it closes the connection
}

From the documentation:

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement

Your resource is the MongoClient instance, which will be automatically closed after the last operation inside the try clause. As you assigned the mongoClient value to your client variable, once the try-clause is finished and the mongoClient closed, client will reference a closed session.

Upvotes: 2

Gopinath
Gopinath

Reputation: 4957

The above observation of connection being closed is as per the intended functionality of the 'try with resources' feature of Java.

The desired requirement of keeping the connection active can be achieved by using a regular try ... catch ... finally block with mongoClient.close() called explicitly for closing the connection.

Moreover, if the requirement is to call the method from a different class, then the code for closing the connection need to be placed in a different method.

Working code snippets:

(a) Connect to MongoDB, fetch data and close connection:

    public void myMongoDBClient() {
        MongoClient mongoClient;
        String uri = "mongodb-connection-uri";
        try {
             mongoClient = new MongoClient(uri)

             // Fetch data from mongodb
             // Other statements


        } catch (Exception ex) {
           // Error handling

        } finally {
           // Close the conection
           mongoClient.close();
        }
    }

(b) Call mongodb client from other classes:

public class MyMongoDBClient {

    private static MongoClient mongoClient = null;
    private static String uri = "mongodb-connection-uri";

    public static void initializeClient() {
        try {
             mongoClient = new MongoClient(uri)

        } catch (Exception ex) {
           // Error handling

        } finally {
           // Close the conection
           mongoClient.close();
        }
    }

   public static void fetchData() throws Exception {
       // Code for fetching data
       // Can be called multiple times from external classes
   }

  public static void close() throws Exception {
      // Close connection.
      // Can be called once from an external class
      mongoClient.close();
  }


}

Upvotes: 0

Related Questions