---
title: "(转)java 数据库连接池的实现代码"
author: "星海孤舟"
date: "2010-12-22T12:30:41Z"
tags: ["JDBC", "Java", "SQL", "thread"]
categories: ["企业架构"]
slug: "java"
draft: false
lastmod: "2010-12-22T12:30:41Z"
id: 849191
url: "https://keith3321.iteye.com/blog/849191"
---

### [java **数据库连接池**的**实现代码**](http://xiaobian.iteye.com/blog/111797)

[]()

![复制代码](http://xiaobian.iteye.com/images/icon_copy.gif "java 数据库连接池的实现代码 - secyaher - 隐龙 为了一生的信念")

001. package com.xiaobian;
002. /\**
003. * **数据库连接池**管理类
004. \*/
005. import java.io.\*;
006. import java.sql.\*;
007. import java.util.\*;
008. import java.util.Date;
009. /\**
010. * 管理类DBConnectionManager支持对一个或多个由属性文件定义的**数据库连接池**的
011. * 访问.客户程序可以调用getInstance()方法访问本类的唯一实例
012. \*/
013. public class DBConnectionManager {
014. public static void main(String\[] args) {
015. DBConnectionManager connectionManager = DBConnectionManager.getInstance();
016. Connection conn =  connectionManager.getConnection("idb");
017. try {
018. Thread.sleep(10);
019. } catch (InterruptedException e) {
020. // TODO Auto-generated catch block
021. e.printStackTrace();
022. }
023. Connection conn1 =  connectionManager.getConnection("idb");
024. Connection conn2 =  connectionManager.getConnection("idb");
025. Connection conn3 =  connectionManager.getConnection("idb");
026. Connection conn4 =  connectionManager.getConnection("idb");
027. Connection conn5 =  connectionManager.getConnection("idb");
028. connectionManager.freeConnection("idb", conn);
029. connectionManager.freeConnection("idb", conn1);
030. connectionManager.freeConnection("idb", conn2);
031. connectionManager.freeConnection("idb", conn3);
032. connectionManager.freeConnection("idb", conn4);
033. connectionManager.freeConnection("idb", conn5);
034. Connection conn6 = connectionManager.getConnection("idb");
035. Connection conn7 = connectionManager.getConnection("idb");
036. System.out.println(" conn6 == "+conn6 +" conn7 == "+conn7);
037. }
038. static private DBConnectionManager instance; // 唯一实例
039. static private int clients; //
040. private Vector drivers = new Vector();
041. private PrintWriter log;
042. private Hashtable pools = new Hashtable();
043. /\**
044. * 返回唯一实例.如果是第一次调用此方法,则创建实例
045. \*
046. * @return DBConnectionManager 唯一实例
047. \*/
048. static synchronized public DBConnectionManager getInstance() {
049. if (instance == null) {
050. instance = new DBConnectionManager();
051. }
052. clients++;
053. return instance;
054. }
055. /\**
056. * 建构私有函数以防止其它对象创建本类实例
057. \*/
058. private DBConnectionManager() {
059. init();
060. }
061. /\**
062. * 将连接对象返回给由名字指定的连接池
063. \*
064. * @param name
065. *            在属性文件中定义的连接池名字
066. * @param con
067. *            连接对象
068. \*/
069. public void freeConnection(String name, Connection con) {
070. DBConnectionPool pool = (DBConnectionPool) pools.get(name);
071. if (pool != null) {
072. pool.freeConnection(con);
073. }
074. }
075. /\**
076. * 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数 限制,则创建并返回新连接
077. \*
078. * @param name
079. *            在属性文件中定义的连接池名字
080. * @return Connection 可用连接或null
081. \*/
082. public Connection getConnection(String name) {
083. DBConnectionPool pool = (DBConnectionPool) pools.get(name);
084. //System.out.println(" pool == "+pool);
085. if (pool != null) {
086. return pool.getConnection();
087. }
088. return null;
089. }
090. /\**
091. * 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制, 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接.
092. \*
093. * @param name
094. *            连接池名字
095. * @param time
096. *            以毫秒计的等待时间
097. * @return Connection 可用连接或null
098. \*/
099. public Connection getConnection(String name, long time) {
100. DBConnectionPool pool = (DBConnectionPool) pools.get(name);
101. if (pool != null) {
102. return pool.getConnection(time);
103. }
104. return null;
105. }
106. /\**
107. * 关闭所有连接,撤销驱动程序的注册
108. \*/
109. public synchronized void release() {
110. // 等待直到最后一个客户程序调用
111. if (--clients != 0) {
112. return;
113. }
114. Enumeration allPools = pools.elements();
115. while (allPools.hasMoreElements()) {
116. DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
117. pool.release();
118. }
119. Enumeration allDrivers = drivers.elements();
120. while (allDrivers.hasMoreElements()) {
121. Driver driver = (Driver) allDrivers.nextElement();
122. try {
123. DriverManager.deregisterDriver(driver);
124. log("撤销JDBC驱动程序 " + driver.getClass().getName() + "的注册");
125. } catch (SQLException e) {
126. log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());
127. }
128. }
129. }
130. /\**
131. * 根据指定属性创建连接池实例.
132. \*
133. * @param props
134. *            连接池属性
135. \*/
136. private void createPools(Properties props) {
137. Enumeration propNames = props.propertyNames();
138. while (propNames.hasMoreElements()) {
139. String name = (String) propNames.nextElement();
140. if (name.endsWith(".url")) {
141. String poolName = name.substring(0, name.lastIndexOf("."));
142. //System.out.println(" poolName ||"+poolName+"|");
143. String url = props.getProperty(poolName + ".url");
144. if (url == null) {
145. log("没有为连接池" + poolName + "指定URL");
146. continue;
147. }
148. String user = props.getProperty(poolName + ".user");
149. String password = props.getProperty(poolName + ".password");
150. String maxconn = props.getProperty(poolName + ".maxconn", "0");
151. int max;
152. try {
153. max = Integer.valueOf(maxconn).intValue();
154. } catch (NumberFormatException e) {
155. log("错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);
156. max = 0;
157. }
158. DBConnectionPool pool = new DBConnectionPool(poolName, url,
159. user, password, max);
160. pools.put(poolName, pool);
161. log("成功创建连接池" + poolName);
162. }
163. }
164. }
165. // --------------------------------------------------------------------------------
166. /\**
167. * 读取属性完成初始化
168. \*/
169. private void init() {
170. InputStream fileinputstream = null;
171. try {
172. fileinputstream = new FileInputStream("./src/db.properties");
173. } catch (FileNotFoundException e1) {
174. e1.printStackTrace();
175. }
176. //BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(fileinputstream));
177. //InputStream is = getClass().getResourceAsStream("D:/workspace/UmessageSms/src/db.properties");
178. Properties dbProps = new Properties();
179. try {
180. dbProps.load(fileinputstream);
181. } catch (Exception e) {
182. e.printStackTrace();
183. System.err.println("不能读取属性文件. "
184. + "请确保db.properties在CLASSPATH指定的路径中");
185. return;
186. }
187. String logFile = dbProps.getProperty("logfile",
188. "DBConnectionManager.log");
189. //System.out.println(dbProps.getProperty("logfile"));
190. try {
191. log = new PrintWriter(new FileWriter(logFile, true), true);
192. } catch (IOException e) {
193. System.err.println("无法打开日志文件: " + logFile);
194. log = new PrintWriter(System.err);
195. }
196. loadDrivers(dbProps);
197. createPools(dbProps);
198. }
199. /\**
200. * 装载和注册所有JDBC驱动程序
201. \*
202. * @param props
203. *            属性
204. \*/
205. private void loadDrivers(Properties props) {
206. String driverClasses = props.getProperty("drivers");
207. StringTokenizer st = new StringTokenizer(driverClasses);
208. while (st.hasMoreElements()) {
209. String driverClassName = st.nextToken().trim();
210. try {
211. Driver driver = (Driver) Class.forName(driverClassName)
212. .newInstance();
213. DriverManager.registerDriver(driver);
214. drivers.addElement(driver);
215. log("成功注册JDBC驱动程序" + driverClassName);
216. } catch (Exception e) {
217. log("无法注册JDBC驱动程序: " + driverClassName + ", 错误: " + e);
218. }
219. }
220. }
221. /\**
222. * 将文本信息写入日志文件
223. \*/
224. private void log(String msg) {
225. log.println(new Date() + ": " + msg);
226. }
227. /\**
228. * 将文本信息与异常写入日志文件
229. \*/
230. private void log(Throwable e, String msg) {
231. log.println(new Date() + ": " + msg);
232. e.printStackTrace(log);
233. }
234. /\** \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** \*/
235. /\** \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*内部类DBConnectionPool\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** \*/
236. /\** \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** \*/
237. /\**
238. * 此内部类定义了一个连接池.它能够根据要求创建新连接,直到预定的最 大连接数为止.在返回连接给客户程序之前,它能够验证连接的有效性.
239. \*/
240. class DBConnectionPool {
241. private int checkedOut; // 当前连接数
242. private Vector freeConnections = new Vector(); // 保存所有可用连接
243. private int maxConn; // 此连接池允许建立的最大连接数
244. private String name; // 连接池名字
245. private String password; // 密码或null
246. private String URL; // 数据库的JDBC URL
247. private String user; // 数据库账号或null
248. /\**
249. * 创建新的连接池
250. \*
251. * @param name
252. *            连接池名字
253. * @param URL
254. *            数据库的JDBC URL
255. * @param user
256. *            数据库帐号或 null
257. * @param password
258. *            密码或 null
259. * @param maxConn
260. *            此连接池允许建立的最大连接数
261. \*/
262. public DBConnectionPool(String name, String URL, String user,
263. String password, int maxConn) {
264. this.name = name;
265. this.URL = URL;
266. this.user = user;
267. this.password = password;
268. this.maxConn = maxConn;
269. }
270. /\**
271. * 将不再使用的连接返回给连接池
272. \*
273. * @param con
274. *            客户程序释放的连接
275. \*/
276. public synchronized void freeConnection(Connection con) {
277. // 将指定连接加入到向量末尾
278. freeConnections.addElement(con);
279. checkedOut--;
280. notifyAll(); // 删除等待队列中的所有线程
281. }
282. /\**
283. * 从连接池获得一个可用连接.如果没有空闲的连接且当前连接数小于最大连接
284. * 数限制,则创建新连接.如原来登记为可用的连接不再有效,则从向量删除之, 然后递归调用自己以尝试新的可用连接.
285. \*/
286. public synchronized Connection getConnection() {
287. Connection con = null;
288. //System.out.println(" freeConnections.size() "+freeConnections.size());
289. if (freeConnections.size() &gt; 0) {
290. // 获取向量中第一个可用连接
291. con = (Connection) freeConnections.firstElement();
292. freeConnections.removeElementAt(0);
293. try {
294. if (con.isClosed()) {
295. log("从连接池" + name + "删除一个无效连接");
296. // 递归调用自己,尝试再次获取可用连接
297. con = getConnection();
298. }
299. } catch (SQLException e) {
300. log("从连接池" + name + "删除一个无效连接");
301. // 递归调用自己,尝试再次获取可用连接
302. con = getConnection();
303. }
304. } else if (maxConn == 0 || checkedOut &lt; maxConn) {
305. con = newConnection();
306. }
307. if (con != null) {
308. checkedOut++;
309. }
310. System.out.println("con == "+con);
311. return con;
312. }
313. /\**
314. * 从连接池获取可用连接.可以指定客户程序能够等待的最长时间 参见前一个getConnection()方法.
315. \*
316. * @param timeout
317. *            以毫秒计的等待时间限制
318. \*/
319. public synchronized Connection getConnection(long timeout) {
320. long startTime = new Date().getTime();
321. Connection con;
322. while ((con = getConnection()) == null) {
323. try {
324. wait(timeout);
325. } catch (InterruptedException e) {
326. }
327. if ((new Date().getTime() - startTime) &gt;= timeout) {
328. // wait()返回的原因是超时
329. return null;
330. }
331. }
332. return con;
333. }
334. /\**
335. * 关闭所有连接
336. \*/
337. public synchronized void release() {
338. Enumeration allConnections = freeConnections.elements();
339. while (allConnections.hasMoreElements()) {
340. Connection con = (Connection) allConnections.nextElement();
341. try {
342. con.close();
343. log("关闭连接池" + name + "中的一个连接");
344. } catch (SQLException e) {
345. log(e, "无法关闭连接池" + name + "中的连接");
346. }
347. }
348. freeConnections.removeAllElements();
349. }
350. /\**
351. * 创建新的连接
352. \*/
353. private Connection newConnection() {
354. Connection con = null;
355. try {
356. if (user == null) {
357. con = DriverManager.getConnection(URL);
358. } else {
359. con = DriverManager.getConnection(URL, user, password);
360. }
361. log("连接池" + name + "创建一个新的连接");
362. } catch (SQLException e) {
363. log(e, "无法创建下列URL的连接: " + URL);
364. return null;
365. }
366. return con;
367. }
368. }
369. }