Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Java | How to manage the connection

Tags:

java

mongodb

I am using MongoDB with Java and have some problems and questions about my connection. First of all, how should I connect to Mongo? Should I use a static client and leave it open? Because it takes like 500ms to connect. So it isn't the best idea to always connect it when users want data, is it?

But the next problem is following. When I do some querys i get the error message java.lang.IllegalStateException: The pool is closed or java.lang.IllegalStateException: state should be: open.

So, how should I manage my whole MongoDB connection stuff? Always wait 500ms is way to slow and restart the server after like 10 connections isn't that good. Are there any other good ways?

Thank you for your help!

like image 523
user6586661 Avatar asked Oct 14 '25 02:10

user6586661


1 Answers

how should I connect to Mongo?

As it sounds, you're already using MongoClient, its a good way to go.

The MongoClient class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application.

Should I use a static client and leave it open?

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.

Do I need to explicitly close connection?

No, you don't. And that as well should resolve the error that you're getting.

Here is a Quick Tour on making the connection using MongoClient.

like image 146
Naman Avatar answered Oct 19 '25 13:10

Naman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!