Search code examples
mongodbstaticthread-safetymorphia

Is using Morphia, MongoClient and Datastore as static variables in all of the application rational?


We are developing an application that has like hundreds of user requests every minute or so.

Is using morphia, mongoclient and datastore as static variables rational for all the save, fetch and update requests on mongodb, or should i use separate instances for each request?


Solution

  • It's not a good practice to share one single instance of Mongo, unless all your read/write operations share the same ReadPreference/WritePreference. Normally, we can specify the preference for each single operation. But it's not good to specify the preference everywhere in your code. And if we use GridFS, we can only specify read preference and write preference globally.

    I often create several data stores, each of them with different read preference and write concern. And I managed it with Spring IoC, or any IoC framework.