This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes JDBC and the fly likes Connecting to DB, when? how often? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Connecting to DB, when? how often?" Watch "Connecting to DB, when? how often?" New topic
Author

Connecting to DB, when? how often?

Jean-Michel Vilain
Greenhorn

Joined: Aug 06, 2010
Posts: 17

I'm working on a game server which stores accounts in a mysql DB thru JDBC.

At first, I initiated a connection to the database once and only once: at server start up. All went well until I noticed that after 8 hours of database inactivity, the connection to the database gets broken...
As my code wasn't ready for that behavior, I did a bit of refactoring. Now, every time my server has to perform some database operation, I open a connection. And when the operation is done, I close the database connection.

While refactoring, I was thinking "cool this is how I should have done since the beginning" ... it works but now I'm afraid of performance issue. And maybe other issues I didn't consider?
What do you think?


Designer and developer on Faƫria: Strategy Card Game (www.faeria.net). The server is 100% Java.
@Jiem_ on Twitter (http://twitter.com/Jiem_)
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3606
    
  60

Connection pools were designed for this. Application servers generally provide one. Actually, I don't know of any good introduction to connection pools off the top of my head, try to google around a bit or have a look at your application server documentation.
Wendy Gibbons
Bartender

Joined: Oct 21, 2008
Posts: 1107

To add to martins comments
a connection pool stores connections for you (as creating a connection can be quite slow).
Before giving you one it checks if any of it's connections are still alive, if not it gets you an alive one. So it is a cross between your two methods of database connecting.
Jean-Michel Vilain
Greenhorn

Joined: Aug 06, 2010
Posts: 17

Orite, thanks ;-)
tim fox
Greenhorn

Joined: Oct 18, 2009
Posts: 4
The Apache site has a decent connection pooling tutorial. Their connection pooling product is called DRCP and it is part of Apache Commons.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Connecting to DB, when? how often?
 
Similar Threads
connection pooling
application hangs at closing the database connection
MySQL, JNDI refactoring
How to handle Transaction with JDBC which could not be rollbacked?
que abt weblogic.log