Java/Tomcat/Vaadin/MongoDB

Hi,

I’m creating small webapp with Vaadin (using Java, Tomcat, MongoDB). I have application basically ready, but when testing the MongoDB generates quite many database connections. And I’m a little bit worried that when released it will generate too many and will die or at least slow down (I’m creating mongoDB database in application entrypoint (extends UI) and closing it in finalize method → as far as I understand this created one database connection for each user - which might be overhead)

What are the best practices to handle this?

How to do this so that the MongoDB connection is created only once when Tomcat is started (I know Java MongoDB instance can internally handle up to 10 connections - so that might be enough for me)?

You should use a single Mongo object, so it will do pooling for you. However, if you do use multiple objects, you do need to call .close() explicitly.

From: http://www.mongodb.org/display/DOCS/Java+Tutorial

The Mongo class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given DB cluster and use it across your app. If for some reason you decide to create many mongo intances, note that:

all resource usage limits (max connections, etc) apply per mongo instance to dispose of an instance, make sure you call mongo.close() to clean up resources

Hey, thanks.

Is there easy way to do that (only one MongoDB instance for my Vaadin app)? I mean in servlets there is init() method which is executed only once when the servlet is started (when Tomcat is started), but now in Vaadin the init() is run for each user. Is there similar servlet init() in Vaadin? Singleton?

I think there should be easy way for that - since It’s quite usable and handy to read something once to the memory (some constant parameters, texts which don’t change, etc).

A singleton pattern would do it, yes.

Your can also use Spring data mongoDB.

Here is easy instructions: https://www.mkyong.com/mongodb/spring-data-mongodb-hello-world-example/
Note that your can use POJO as well and mix spring data and mongo java driver (like BasicDBObject) after opening etc.
.