您的位置:首页 > 数据库

再谈远程数据库连接超时问题解决

2014-05-13 08:51 253 查看
经过前期的代码完善,远程数据一旦超时,就要及时释放数据库连接而且要及时关闭.对代码进行了优化把所有关闭及解锁都放在finally块里.代码如下/**

* 更新时间(sms_sent)

* @param applicationId

* @throws SQLException

*/

public synchronized void updateStatusTime(String applicationId) throws SQLException {

this.send_lock.writeLock().lock();

ExecutorService exeServ=Executors.newFixedThreadPool(1, new CustomThreadFactory("TaskEngine-timeout-scheduler", true));

Future future=null;

String sql = "update sms_sent set STATUSTIME=REQUESTTIME where MASSMSID=?";

Connection con = null;

PreparedStatement pstmt = null;

try {

con= ConnectionManager.getConnection();

pstmt = con.prepareStatement(sql);

pstmt.setString(1, applicationId);

future=exeServ.submit(new ExecuteUpdate(pstmt));

future.get(timeout,TimeUnit.MILLISECONDS);

} catch (Exception e) {

throw new SQLException(e);

} finally {

try { pstmt.close(); }

catch (Exception e) { e.printStackTrace(); }

try { con.close(); }

catch (Exception e) { e.printStackTrace(); }

exeServ.shutdown();

this.send_lock.writeLock().unlock();

}

}

下面是实现Callable的类

private class ExecuteUpdate implements Callable{

private PreparedStatement pstmt;

public ExecuteUpdate(PreparedStatement pstmt){

this.pstmt=pstmt;

}

public Integer call() throws Exception {

return pstmt.executeUpdate();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: