BQuadra
BQuadra

Reputation: 819

postgres in a java server info

create server made in Java. The server accept request on port 111, and when a client connect to the server send to it a JSON file. The server receive the JSON then he must store into a postgres database.

My question is how to manage the postgres connection.

Should I create only one Connection and synchronize it for every client request or create a new connection for every client connected to the server.

I mean:

--------- Only one connection: --------------

The server create the only one connection with

_connection = DriverManager.
   getConnection("jdbc:postgresql:"+_dbName, _username, _password);

and for every clients use this connection

syncronize(_connection) { send data to database }

--------- A connection for every client -------------

The server when accept a client request create a new connection for the connected client

_clientConnection = DriverManager.
   getConnection("jdbc:postgresql:"+_dbName, _username, _password);

And every client has a personal connection.

Can anyone explain what is the best working practice for do this stuff? I think is the same with MySQL.

Upvotes: 0

Views: 129

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

The best practice is to use a pool of connections. This makes sure that

  • multiple clients can access the database concurrently
  • the number of open connections always stays reasonable, and doesn't put the server or database to its knees in case of a high number of concurrent requests
  • connections are not constantly opened and closed. Opening a connection is a time and memory consuming operation

There are several free connection pools available (C3P0, DBCP, etc.). Google is your friend.

Upvotes: 4

Related Questions