Opening a new database connection for every client that connects to the server application? Opening a new database connection for every client that connects to the server application? database database

Opening a new database connection for every client that connects to the server application?


Option 3: use a connection pool. Every time you want to connect to the database, you get a connection from the pool. When you're done with it, you close the connection to give it back to the pool.

That way, you can

  • have several clients accessing the database concurrently (your option 1 doesn't allow that)
  • have a reasonable number of connections opened and avoid bringing the database to its knees or run out of available connections (your option 2 doesn't allow that)
  • avoid opening new database connections all the time (your option 2 doesn't allow that). Opening a connection is a costly operation.

Basically all server apps use this strategy. All Java EE servers come with a connection pool. You can also use it in Java SE applications, by using a pool as a library (HikariCP, Tomcat connection pool, etc.)


I would suggested a third option, database connection pooling. This way you create a specified number of connections and give out the first available free connection as soon as it becomes available. This gives you the best of both worlds - there will almost always be free connections available quickly and you keep the number of connections the database at a reasonable level. There are plenty of the box java connection pooling solutions, so have a look online.


Just use connection pooling and go with option 2. There are quite a few - C3P0, BoneCP, DBCP. I prefer BoneCP.