views:

79

answers:

3

Hi, I'm using a singleton class for a PostgresSQL connection inside a servelet. The problem is that once it is open it works for a while (I guess until some timeout), and then it starts throwing a I/O exception. Any idea what is happening to the singleton class inside Tomcat VM? Thanks

+3  A: 

I have no idea. Just do the right thing and do not reinvent the wheel. Use a DataSource, either obtain it via JNDI (see http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html), or do it yourself (I like using Spring, but if your web application is very simple, it's probably overkill).

Use a DataSource.

alex
A: 

and then it starts throwing a I/O exception

Well, what is the exception exactly?

Also, as a note, it's safe to use the same Postgres JDBC connection from multiple threads, but it is not recommended to do so.

matt b
+1  A: 

There's no singleton inside Tomcat; that's just the way connections work when you only have one and keep it open for a long time. It's called "timeout".

This design cannot scale. A better solution is to keep connections open for as short a time as possible. Your code should open a connection, use it, and close it in transaction scope.

You should also set up a connection pool in Tomcat.

duffymo