Majid Azimi
Majid Azimi

Reputation: 5745

How to use one instance of MongoClient in java application server

According to mongodb java concurrency driver we can use one instance of MongoClient for multiple threads for example inside application servers. The only way I know to do this is to create MongoClient in static block:

static {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
}

the problem is I can't catch MongoException and return some helpfull information to user. So how to share a single instance of MongoClient between multiple threads inside Java EE application servers?

Upvotes: 0

Views: 1610

Answers (1)

TheZuck
TheZuck

Reputation: 3631

You can do one of the following:

  1. Create a service class and initiate the mongo connection lazily on first request, showing an error when you fail
  2. Add a try catch and remember the error statically (I really don't like this one! But better than failing on exception in static context)
  3. Use spring to initialize mongo (my preferred option)

Upvotes: 1

Related Questions