Analyzing the Cost of Establishing a MySQL Database Connection in Java
This article investigates the time consumption of creating and closing a MySQL connection from a Java application, measuring each network and protocol step with Wireshark and code examples, and demonstrates why connection pooling is essential for high‑traffic web services.
The author explores the detailed cost of establishing a MySQL database connection in a Java web application, aiming to quantify the latency of each stage from TCP handshake to authentication.
Using a minimal Java snippet:
Class.forName("com.mysql.jdbc.Driver");
String name = "shine_user";
String password = "123";
String url = "jdbc:mysql://172.16.100.131:3306/clever_mg_test";
Connection conn = DriverManager.getConnection(url, name, password);
// program ends, connection closed abruptlyWireshark captures reveal that MySQL uses a binary TCP protocol and that establishing a connection involves three main steps: (1) TCP three‑way handshake, (2) server handshake message, and (3) client authentication packet.
After successful authentication, additional configuration exchanges (character set, autocommit, etc.) occur before any SQL commands can be issued.
Measuring the elapsed time from the start of the TCP handshake to the forced termination of the process (excluding the final RST packet) yields approximately 225 ms:
10.416042 - 10.190799 = 0.225243s = 225.243msWhen the connection is properly closed with Connection.close() , the shutdown sequence includes a MySQL protocol close request followed by a TCP four‑way termination, taking about 183 ms:
747.284311 - 747.100954 = 0.183357s = 183.357msFor a site with 20 000 daily active users each making five requests, the naive approach of opening a new connection for every request would consume roughly 4 hours of CPU time per day (100 000 requests × 150 ms per connection), highlighting the necessity of a connection pool.
The article also notes that as traffic grows, connection pooling alone may not suffice; additional techniques such as caching, SQL statement pre‑compilation, and load balancing should be considered.
In summary, establishing a database connection is relatively expensive, and developers should avoid frequent connection creation by employing pooling and related performance‑optimizing strategies.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.