---
title: "使用DBCP连接池检测未关闭的数据库连接"
author: "LucasLee"
date: "2006-11-17T14:22:21Z"
tags: []
categories: ["数据库"]
slug: "dbcp"
draft: false
lastmod: "2006-11-17T14:22:21Z"
id: 34743
url: "https://lucaslee.iteye.com/blog/34743"
---

我一直使用DBCP连接池，效果还不错。
最近因为朋友的一个J2EE应用一上连接池，很快就会报connection pool exhausted的错误，所以
特地研究了一下如何自动检测未关闭的数据库连接的技术。

研究了tomcat文档中DataSource一章，发现有专门的Preventing dB connection pool leaks一节，
设置数据源的removeAbandoned="true"，removeAbandonedTimeout="60"，logAbandoned="true"几个属性就可以了。
DBCP会自动把超过timeout时间仍未关闭的连接强制关闭，并且打出异常信息(包含打开连接的代码位置)。
但是要注意，不能依赖这种方式关闭连接，是有一定风险的，比如万一页面操作数据库的时间偶尔超过了
timeout的时间，那会造成执行错误。

对我来说，这个方法最好的用法就是用来检测未关闭的连接，然后修改程序，显式的关闭连接。

一个经验需要说一下，DBCP的log会输出到控制台，如果使用log4j,需要设置log4j.xml中的console appender的threshold为debug.