Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to explicitly close connection?

Tags:

java

mongodb

I'm holding one instance of MongoClient and DB in my application, and every time that I want to execute some operation I call getCollection().
I'm wondering if I need to explicitly close the connection, just like connection.close() in JDBC.

To emphasize, I have only one MongoClient instance. My question is not about closing MongoClient but closing the connections I believe it opens when I'm calling getCollection().

like image 683
danieln Avatar asked Nov 12 '13 19:11

danieln


People also ask

Do we need to close connection in connection pool?

Yes, certainly you need to close the pooled connection as well. It's actually a wrapper around the actual connection. It wil under the covers release the actual connection back to the pool.

Is con close () necessary?

No, they wouldn't be closed. If getConnection() creates a new Connection, then the only thing that will happen at the end of the method is that the Connection could be garbage collected. But the GC won't call the close() method for you.

What happens if connection is not closed?

If we don't close the connection, it will lead to connection memory leakage. Until application server/web server is shut down, connection will remain active, even if the user logs out.

Should I close MongoClient?

In general, it is always a good practice to close the resources after they are used and before exiting the application. The MongoClient#close() method API documentation says: Close the client, which will close all underlying cached resources, including, for example, sockets and background monitoring threads.


2 Answers

No, you do not need to close connections to DB - your only connection is via MongoClient and as the documentation states - it handles connection pooling for you.

The only resource that you would want to clean up would be a cursor which you should close() when you're done with it.

like image 163
Asya Kamsky Avatar answered Oct 24 '22 00:10

Asya Kamsky


You should close if you have many MongoClient.

The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

MongoClient.close() to clean up resources

MongoClient.close() - closes the underlying connector, which in turn closes all open connections. Once called, this Mongo instance can no longer be used.

More: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/

like image 8
MariuszS Avatar answered Oct 24 '22 01:10

MariuszS