Explanation of the following error:
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.
Summary:
You have opened more than the allowable limit for database connections. You ran something like this: Connection conn = myconn.Open(); inside the loop and forgot to run conn.close(); . Just because your class is destroyed and garbage collection does not release the database connection. The quickest fix for this is to make sure you have the following code with any class that creates the connection:
protected void finalize() throws Throwable { try { your_connection.close(); } catch (SQLException e) { e.printStackTrace(); } super.finalize(); }
Put this code in any class where you create the connection. Then, when your class collects garbage, your connection will be released.
Run this SQL to allow valid postgresql max connections:
show max_connections;
The default is 100. PostgreSQL with good hardware can support several hundred connections at once. If you want to have thousands, you should consider using pooling software to reduce connection overhead.
Take a look at who / what / when / where holds your connections:
SELECT * FROM pg_stat_activity;
Number of currently used compounds:
SELECT COUNT(*) from pg_stat_activity;
Debugging strategy
You can specify different usernames / passwords for programs that may not release connections to find out which one is there, and then look in pg_stat_activity to see which one is not cleared after itself.
Perform a full trace of the exception stack when connections cannot be created, and follow the code where you create the new Connection , make sure that each line of code in which you create the connection ends with connection.close();
How to set max_connections above:
max_connections in postgresql.conf sets the maximum number of concurrent connections to the database server.
- First find the postgresql.conf file
- If you do not know where it is, query the database using sql:
SHOW config_file; - My is in:
/var/lib/pgsql/data/postgresql.conf - Log in as root and edit this file.
- Search for the string: "max_connections".
- You will see a line with the text
max_connections=100 . - Set this number more, check the limit for your version of postgresql.
- Restart the postgresql database for the change to take effect.
What are the maximum max_connections?
Use this query:
select min_val, max_val from pg_settings where name='max_connections';
I get the value 8388607 , theoretically, what you are most allowed to have, but then the escape process can eat thousands of connections and surprise your database is not responsible for rebooting. If you had reasonable max_connections, such as 100. The abusive program will be denied a new connection.