JDBC Connection Pool and MySQL
September 7th, 2007The web application I created is running on Apache Tomcat 6.0.14 with MySQL database. I decided to setup a data source in ${tomcat-home}/conf/Catalina/www.somedomain.com/ROOT.xml. The XML file looked like:
<context docbase="/wars/application.war">
<resource>
name="jdbc/ApplicationDS"
auth="Container"
type="javax.sql.DataSource"
username="db_user"
password="db_password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/db"/>
</resource>
</context>
Unfortunately the connections to the server closed after 8 hours of inactivity with the following exception.
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException:
No operations allowed after connection closed.
Connection was implicitly closed due to underlying
exception/error:
** BEGIN NESTED EXCEPTION **
com.mysql.jdbc.CommunicationsException
MESSAGE: Communications link failure due to
underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: Broken pipe
STACKTRACE:
java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(...:92)
at java.net.SocketOutputStream.write(...:136)
...
I googled about the problem with JDBC connection pools and MySQL, and found a lot of information how to fix it. Most of the hints were to add autoReconnect=true to the DB connection URL (e.g. url=”jdbc:mysql://localhost:3306/db?autoReconnect=true”). But I read, that this may cause problems and will be removed in later versions of the JDBC driver.
The correct usage and configuration of the JDBC connection pool for MySQL can be found MySQL Reference Manual: Using Connector/J with J2EE. I changed my Tomcat configuration to the XML below, and since then I had no problems anymore:
<context docbase="/wars/application.war">
<resource>
name="jdbc/ApplicationDS"
auth="Container"
type="javax.sql.DataSource"
maxActive=”50″
maxIdle=”10″
validationQuery=”SELECT 1″
testOnBorrow=”true”
testWhileIdle=”true”
timeBetweenEvictionRunsMillis=”10000″
minEvictableIdleTimeMillis=”60000″
username=”db_user”
password=”db_password”
driverClassName=”com.mysql.jdbc.Driver”
url=”jdbc:mysql://localhost:3306/db”/>
</resource>
</context>



Subscribe to this Weblog