While working on my Java Game Server, I came across a frustrating error. The JDBC and MySQL connection will fail after 8hrs of being idle. Meaning after 8hrs, any succeeding connection request will throw an exception:
com.mysql.jdbc.CommunicationsException
Communications link failure due to underlying exception
I've been figuring out what's wrong so I tried searching the web for a work around or solution. Below are the possible solutions:
1. Increase the MySQL wait_timeout value (in seconds) to a ridiculously big value (Example: 1 year = 31,536,000 secs) in \etc\ my.cnf config.
2. Use JDBC connection polling. There are lots of free code availabe on the net. Go google ;-)
http://pdf.coreservlets.com/CSAJSP-Chapter18.pdf
3. My simple solution is to register the driver whenever you need to get the connection and unregister after using it. You also need to create a thread to keep the connection alive every hour.
I believe it will be clearer if I'll post my code here:
class ConnectionKeepAlive extends Thread
{
private Database m_database;
ConnectionKeepAlive(Database database)
{
this.m_database = database;
}
public void run()
{
while(true)
{
try
{
sleep(Constants.TIME_ONE_HOUR);
}
catch(InterruptedException ie) {}
m_database.connectionKeepAlive();
}
}
}
//==============
public class Database{
ConnectionKeepAlive m_keepAlive = null;
ConnectionPool m_connectionPool = null;
Database()
{
try
{ m_connectionPool = new ConnectionPool(Constants.JDBC_MYSQL_DRIVER, Constants.JDBC_MYSQL_URL,
Constants.JDBC_MYSQL_USERNAME,
Constants.JDBC_MYSQL_PASSWORD,
Constants.JDBC_MIN_POOL_SIZE,
Constants.JDBC_MAX_POOL_SIZE,
true);
}
catch(Exception e)
{
System.exit(1);
}
m_keepAlive = new ConnectionKeepAlive(this);
m_keepAlive.start();
}
public synchronized Connection getConnection() throws SQLException
{
return m_connectionPool.getConnection();
}
public synchronized void connectionKeepAlive()
{
Statement statement = null;
Connection conn = null;
String query = "";
try
{
conn = getConnection();
statement = conn.createStatement();
query = "SELECT CURRENT_DATE()";
}
catch(Exception e) { }
finally
{
try
{
if (statement != null)
{
statement.close();
}
if (conn != null)
{
m_connectionPool.free(conn);
conn.close();
}
}
catch(Exception e) { }
}
}
}
Disclaimer: Use at your own RISK. I am NOT responsible for any damage that this code will cause in your PC. Good luck ;-)
Friday, November 03, 2006
Subscribe to:
Post Comments (Atom)

0 comments:
Post a Comment