4

I'm using the standard MongoDB Java driver to roll my own DAOs. I'm aware that all of my DAOs can share the same Mongo instance, but should all of my DAOs accessing the same database share the same DB object or are there good reasons for a new DB object to be requested or each?

Thanks!

Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
HolySamosa
  • 9,011
  • 14
  • 69
  • 102

2 Answers2

2

You can use shared instances of the Mongo class, the DB class and the DBCollection class if that proves to be practical for you. Whether or not you want to from a design perspective is up to you. I'd definitely use Mongo instances as singletons since they're relatively heavy weight (have their own thread pool etc.)

Remon van Vliet
  • 18,365
  • 3
  • 52
  • 57
1

The "good reason" to share the Mongo object is built-in connection pooling. If it's not practical to share your Mongo object instance between DAOs, then that's a good reason (in my opinion), to create new instances. If it is practical, then you should share it.

Remember that you should use .close() when you're done using a Mongo instance, to prevent leaving open connections.

Eve Freeman
  • 32,467
  • 4
  • 86
  • 101
  • Mongo instances are a relatively heavy weight object so I would not use an instance per DAO if the DAO are short lived (e.g. request scoped) – Remon van Vliet Jan 25 '12 at 17:04
  • @RemonvanVliet I agree. Best practice is to have the singleton that you can share. – Eve Freeman Jan 25 '12 at 17:19
  • Thanks for the responses! I do know that I should share the Mongo object, but I was wondering whether the DB objects should / should not be shared as well. I think Remon answered that. Thanks for the tip on close(). – HolySamosa Jan 25 '12 at 18:31