Skip to lesson

Why unclosed connections break applications

A web app runs well for hours, then every page fails with "Too many connections", though no single request looks wrong. The usual cause is one method that opens a connection and forgets to close it.

What a connection holds on the server

max_connections is the MySQL setting for the most connections the server accepts at the same time. Every open connection uses one slot, one thread and some memory until it is closed.

A database connection is an open session between your program and the MySQL server. Example 1 asks MySQL for the numbers that describe it.

Example 1 · What MySQL reports about connections

Runs in: a Maven project with the MySQL driver and the ShopLite database

ServerLimitsDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class ServerLimitsDemo {    public static void main(String[] args) throws SQLException {        String url = System.getenv("DB_URL");            // jdbc:mysql://localhost:3306/shoplite        String user = System.getenv("DB_USER");        String password = System.getenv("DB_PASSWORD");
        try (Connection conn = DriverManager.getConnection(url, user, password);             Statement st = conn.createStatement()) {            System.out.println("My connection id : " + firstValue(st, "SELECT CONNECTION_ID()"));            System.out.println("max_connections  : " + firstValue(st, "SELECT @@max_connections"));            System.out.println("Threads_connected: "                    + firstValue(st, "SELECT VARIABLE_VALUE FROM performance_schema.global_status"                            + " WHERE VARIABLE_NAME = 'Threads_connected'"));        }    }
    static String firstValue(Statement st, String sql) throws SQLException {        try (ResultSet rs = st.executeQuery(sql)) {            rs.next();            return rs.getString(1);        }    }}
Sample output
My connection id : 145
max_connections  : 151
Threads_connected: 1

What this code does

  • Threads_connected is 1 because this program's own connection is the only one open. A MySQL Workbench tab or a mysql window would add to it, and the connection id is different on every run.
  • The URL, user and password come from the DB_URL, DB_USER and DB_PASSWORD environment variables, as in the Connecting to a Database module, so no password is written in the code.
  • firstValue closes each ResultSet it opens; the Statement and the Connection are closed by the try (...) in main.

On MySQL 8.4 the default max_connections is 151. That sounds like plenty until a busy app, or a bug that forgets to close, uses it up. Closing a connection gives the thread, the memory and the slot back at once.

Example 1 prints three numbers:

  • CONNECTION_ID(): the number MySQL gives this session. Every new connection gets a new number.
  • @@max_connections: the server's limit on open connections.
  • Threads_connected: how many connections are open right now, from every program and user.

A leak in a loop: 'Too many connections'

A connection leak is a database connection that a program opens and never closes. Every leaked connection keeps its slot, until none are left and every user of the app gets an error.

A method that opens a connection on every call and never closes it still returns the right answer each time. Example 2 runs it until the server has no free slots left.

The server has 10 connection slots. Each call that forgets to close its connection keeps one slot in Sleep state: after seven calls, three slots are free. When all ten are used, the next request fails with Too many connections, and every user of the app is affected.

Example 2 · A leaking method runs the server out of slots

Runs in: a Maven project with the MySQL driver and the ShopLite database, with max_connections set to 10

LeakDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;
public class LeakDemo {    static final String URL = System.getenv("DB_URL");    static final String USER = System.getenv("DB_USER");    static final String PASSWORD = System.getenv("DB_PASSWORD");
    // In a real app leaked connections stay reachable (from a pool, a cache or a busy thread).    // This list plays that part, so the garbage collector cannot quietly clean them up.    static final List<Connection> stillReachable = new ArrayList<>();
    // BUG: opens a connection, a statement and a result set, and closes none of them    static int countProducts() throws SQLException {        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);        stillReachable.add(conn);        Statement st = conn.createStatement();        ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM products");        rs.next();        return rs.getInt(1);    }
    public static void main(String[] args) {        for (int request = 1; request <= 20; request++) {            try {                int count = countProducts();                System.out.println("Request " + request + ": " + count + " products");            } catch (SQLException e) {                System.out.println("Request " + request + " failed");                System.out.println(e.getClass().getName());                System.out.println(e.getMessage());                return;            }        }    }}
Sample output
Request 1: 15 products
Request 2: 15 products
Request 3: 15 products
Request 4: 15 products
Request 5: 15 products
Request 6: 15 products
Request 7: 15 products
Request 8: 15 products
Request 9: 15 products
Request 10: 15 products
Request 11 failed
java.sql.SQLNonTransientConnectionException
Too many connections

What this code does

  • Requests 1 to 10 each leave one connection open. Request 11 needs an eleventh connection, and MySQL refuses it with error 1040, Too many connections. If another program is connected too, the failure comes one request earlier.
  • From now on every part of the app that needs the database fails, even code with no bug. On a server with the default limit the same thing happens after 151 leaked connections, usually in the middle of a busy day.
  • The stillReachable list plays the part of a pool, cache or busy thread. Without it, the driver's cleanup thread may close a few unreachable connections, and the failure moves to a later, random request.

To see it in seconds instead of hours, lower the limit on your own practice server, logged in as root: SET GLOBAL max_connections = 10;. Afterwards put it back with SET GLOBAL max_connections = 151; (a server restart also resets it). Never try this on a shared or production server.

Predict the output

Which call fails?

Read the code and pick what it prints.

max_connections is 3 and the garbage collector has not run.

static int count() throws SQLException {
Connection con = DriverManager.getConnection(URL, USER, PASS);
return 15;
}
// four calls in a row
count(); count(); count(); count();
Connector/J has a safety net: a background thread closes connections that the garbage collector finds unreachable. It runs at unpredictable times, so a leak can hide in a small test and appear under real load. Never rely on it.

Watching open connections with SHOW PROCESSLIST

SHOW PROCESSLIST is a MySQL command that lists every open connection with its Id, User, database (db), Command, Time in seconds and Info.

A leak looks like many rows in Sleep state whose Time keeps growing while the app is idle. Run these two commands, then see Example 3.

SQL
SHOW PROCESSLIST;SHOW GLOBAL STATUS LIKE 'Threads_connected';

Example 3 · Leaked connections in SHOW PROCESSLIST

Runs in: a Maven project with the MySQL driver and the ShopLite database

ProcessListDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;
public class ProcessListDemo {    static final String URL = System.getenv("DB_URL");    static final String USER = System.getenv("DB_USER");    static final String PASSWORD = System.getenv("DB_PASSWORD");
    public static void main(String[] args) throws Exception {        List<Connection> leaked = new ArrayList<>();        for (int i = 0; i < 3; i++) {            Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);            conn.createStatement().executeQuery("SELECT COUNT(*) FROM customers");            leaked.add(conn);                      // opened, used, never closed        }        Thread.sleep(5000);                        // the app carries on with other work
        try (Connection admin = DriverManager.getConnection(URL, USER, PASSWORD);             Statement st = admin.createStatement();             ResultSet rs = st.executeQuery("SHOW PROCESSLIST")) {            System.out.printf("%-4s %-13s %-9s %-8s %-5s %s%n", "Id", "User", "db", "Command", "Time", "Info");            while (rs.next()) {                System.out.printf("%-4d %-13s %-9s %-8s %-5d %s%n",                        rs.getLong("Id"), rs.getString("User"), rs.getString("db"),                        rs.getString("Command"), rs.getLong("Time"), rs.getString("Info"));            }        }
        for (Connection conn : leaked) {           // tidy up so the demo leaves nothing behind            conn.close();        }    }}
Sample output
Id   User          db        Command  Time  Info
158  shoplite_app  shoplite  Sleep    6     null
159  shoplite_app  shoplite  Sleep    5     null
160  shoplite_app  shoplite  Sleep    5     null
161  shoplite_app  shoplite  Query    0     SHOW PROCESSLIST

What this code does

  • The three leaked connections show Sleep with Time 5 or 6: they finished their query seconds ago and are just sitting there. In a leaking app this list keeps growing and the times keep rising.
  • The last row is the connection that ran SHOW PROCESSLIST itself; its Command is Query and Info shows the SQL it is running.
  • Ids differ on every run. Running the same SHOW PROCESSLIST; in the mysql client while your app is idle is the quickest leak check there is.

A normal user sees only their own connections; root, or a user with the PROCESS privilege, sees everyone's. MySQL keeps one extra slot for an administrator, so root can still log in and look when the app already gets Too many connections.

Statements and result sets also hold resources

A PreparedStatement and its ResultSet use memory in your program, and prepared statements can use memory on the server too. Example 4 counts statements piling up there.

Example 4 · Unclosed prepared statements pile up on the server

Runs in: a Maven project with the MySQL driver and the ShopLite database

StatementLeakDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import java.util.Properties;
public class StatementLeakDemo {    public static void main(String[] args) throws SQLException {        Properties props = new Properties();        props.setProperty("user", System.getenv("DB_USER"));        props.setProperty("password", System.getenv("DB_PASSWORD"));        props.setProperty("useServerPrepStmts", "true");   // MySQL keeps each prepared statement on the server
        try (Connection conn = DriverManager.getConnection(System.getenv("DB_URL"), props)) {            List<PreparedStatement> notClosed = new ArrayList<>();            for (int i = 1; i <= 500; i++) {                PreparedStatement ps = conn.prepareStatement("SELECT name FROM products WHERE product_id = ?");                ps.setInt(1, i % 15 + 1);                ps.executeQuery().next();            // the statement and its result set stay open                notClosed.add(ps);            }            System.out.println("After 500 lookups : " + preparedOnServer(conn));
            for (PreparedStatement ps : notClosed) {                ps.close();            }            System.out.println("After closing them: " + preparedOnServer(conn));        }    }
    static String preparedOnServer(Connection conn) throws SQLException {        try (Statement st = conn.createStatement();             ResultSet rs = st.executeQuery("SHOW GLOBAL STATUS LIKE 'Prepared_stmt_count'")) {            rs.next();            return rs.getString("Value") + " prepared statements on the server";        }    }}
Sample output
After 500 lookups : 500 prepared statements on the server
After closing them: 0 prepared statements on the server

What this code does

  • With useServerPrepStmts=true (passed here in a Properties object), each prepareStatement call creates a statement on the server. 500 lookups without close() leave 500 of them there, all on one connection.
  • Closing the statements drops the count to 0. Prepared_stmt_count is server-wide, so other programs can add to it on your machine.
  • A loop like this inside a long-running app eventually hits max_prepared_stmt_count and every new prepareStatement call fails.

With useServerPrepStmts=true, MySQL keeps every prepared statement on the server until it is closed, and refuses new ones once max_prepared_stmt_count (16382 by default) is reached.

The JDBC rules say closing a statement closes its result set, and closing a connection closes its statements. That is a backstop, not a plan: a long-lived connection (and, later, a pooled one that is never really closed) keeps every statement you forgot. Close each object as soon as you are done with it.

The old way: close calls in a finally block

Before Java 7, cleanup went into a finally block, which always runs. You declared the variables as null, opened them inside the try, and closed them in finally. Example 5 shows how this breaks.

Example 5 · Why close calls in finally go wrong

FragileFinallyDemo.javaJava
class FakeResource {    private final String name;    private final boolean failOnClose;
    FakeResource(String name, boolean failOnOpen, boolean failOnClose) throws Exception {        if (failOnOpen) {            throw new Exception("could not open " + name);        }        this.name = name;        this.failOnClose = failOnClose;        System.out.println("  open  " + name);    }
    void close() throws Exception {        if (failOnClose) {            throw new Exception(name + " close failed");        }        System.out.println("  close " + name);    }}
public class FragileFinallyDemo {    // The pre-Java-7 style: three variables, then three close calls in finally    static void report(boolean statementFailsToOpen, boolean resultSetFailsToClose) throws Exception {        FakeResource conn = null;        FakeResource st = null;        FakeResource rs = null;        try {            conn = new FakeResource("connection", false, false);            st = new FakeResource("statement", statementFailsToOpen, false);            rs = new FakeResource("result set", false, resultSetFailsToClose);            System.out.println("  reading rows...");        } finally {            rs.close();            st.close();            conn.close();        }    }
    public static void main(String[] args) {        System.out.println("Run 1: everything works");        tryReport(false, false);        System.out.println("Run 2: the result set fails to close");        tryReport(false, true);        System.out.println("Run 3: the statement fails to open");        tryReport(true, false);    }
    static void tryReport(boolean statementFailsToOpen, boolean resultSetFailsToClose) {        try {            report(statementFailsToOpen, resultSetFailsToClose);        } catch (NullPointerException e) {            System.out.println("  caught: NullPointerException from the finally block");        } catch (Exception e) {            System.out.println("  caught: " + e.getMessage());        }    }}
Output
Run 1: everything works
  open  connection
  open  statement
  open  result set
  reading rows...
  close result set
  close statement
  close connection
Run 2: the result set fails to close
  open  connection
  open  statement
  open  result set
  reading rows...
  caught: result set close failed
Run 3: the statement fails to open
  open  connection
  caught: NullPointerException from the finally block

What this code does

  • Run 1 is the happy path: everything opens and closes in reverse order. FakeResource stands in for a connection, statement and result set so you can make each step fail on purpose.
  • Run 2: rs.close() throws, so st.close() and conn.close() never run. The statement and the connection leak, and nothing on the screen says so.
  • Run 3: the statement fails to open, so rs and st are still null. rs.close() throws a NullPointerException, which replaces the real error could not open statement, and the connection leaks too.

Example 6 · The careful finally version, and how long it is

Runs in: a Maven project with the MySQL driver and the ShopLite database, with max_connections set to 10

CarefulFinallyDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class CarefulFinallyDemo {    static final String URL = System.getenv("DB_URL");    static final String USER = System.getenv("DB_USER");    static final String PASSWORD = System.getenv("DB_PASSWORD");
    // Correct, but look how much of it is cleanup    static int countProducts() throws SQLException {        Connection conn = null;        Statement st = null;        ResultSet rs = null;        try {            conn = DriverManager.getConnection(URL, USER, PASSWORD);            st = conn.createStatement();            rs = st.executeQuery("SELECT COUNT(*) FROM products");            rs.next();            return rs.getInt(1);        } finally {            if (rs != null) {                try { rs.close(); } catch (SQLException e) { System.out.println("rs.close failed: " + e); }            }            if (st != null) {                try { st.close(); } catch (SQLException e) { System.out.println("st.close failed: " + e); }            }            if (conn != null) {                try { conn.close(); } catch (SQLException e) { System.out.println("conn.close failed: " + e); }            }        }    }
    public static void main(String[] args) throws SQLException {        for (int request = 1; request <= 50; request++) {            int count = countProducts();            if (request % 10 == 0) {                System.out.println("Request " + request + ": " + count + " products");            }        }        System.out.println("50 requests, no 'Too many connections'");    }}
Output
Request 10: 15 products
Request 20: 15 products
Request 30: 15 products
Request 40: 15 products
Request 50: 15 products
50 requests, no 'Too many connections'

What this code does

  • Each close has its own null check and its own try/catch, in reverse order of opening. Now a failing close cannot stop the others, and a half-opened set of objects cannot cause a NullPointerException.
  • 50 requests on a server limited to 10 connections all work, which proves nothing leaks. The return inside try is safe: finally runs after the value is read and before the method returns.
  • Fourteen lines of cleanup for three lines of real work is why Java 7 added try-with-resources.

It looks simple and breaks in two ways. If one close() throws, the lines after it never run, so the remaining objects leak. If opening fails halfway, some variables are still null, and calling close() on them throws a NullPointerException that hides the real error. The safe version needs a null check and its own try/catch around every close; Example 6 shows it, and how long it gets.

Find the bug

Find the wrong line

Select the line that is wrong.

When the connection cannot be opened, a NullPointerException hides the real error. Which line?

Round 1 of 2
The next lesson replaces all of this with try-with-resources, which closes everything correctly in one line per resource.

Next step

Check your understanding

12 quick questions