- 浏览: 217354 次
- 性别:
- 来自: 北京
-
最新评论
-
xupo:
tzg157 写道qinkangwencai 写道别误导大家了 ...
Java多线程编程环境中单例模式的实现 -
xupo:
qinkangwencai 写道别误导大家了行吗?double ...
Java多线程编程环境中单例模式的实现 -
qaddafi2008:
内部静态类的方法貌似是目前最好的解法了!
Java多线程编程环境中单例模式的实现 -
sanshizi:
学习了
Java多线程编程环境中单例模式的实现 -
tzg157:
qinkangwencai 写道别误导大家了行吗?double ...
Java多线程编程环境中单例模式的实现
/** * Title: ConnectPool.java * Description: 连接池管理器 * Copyright: Copyright (c) 2002/12/25 * Company: * Author : * Version 2.0 */ import java.io.*; import java.sql.*; import java.util.*; import java.util.Date; /** * 管理类DBConnectionManager支持对一个或多个由属性文件定义的数据库连接 * 池的访问.客户程序可以调用getInstance()方法访问本类的唯一实例. */ public class ConnectPool { static public ConnectPool instance; // 唯一实例 static public int clients; public Vector drivers = new Vector(); //驱动 public PrintWriter log; public Hashtable pools = new Hashtable(); //连接 /** * 返回唯一实例.如果是第一次调用此方法,则创建实例 * * @return DBConnectionManager 唯一实例 */ static synchronized public ConnectPool getInstance() { if (instance == null) { instance = new ConnectPool(); } clients++; return instance; } /** * 建构函数私有以防止其它对象创建本类实例 */ public ConnectPool() { init(); } /** * 将连接对象返回给由名字指定的连接池 * * @param name 在属性文件中定义的连接池名字 * @param con 连接对象 */ public void freeConnection(String name, Connection con) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); if (pool != null) { pool.freeConnection(con); } else { System.out.println("pool ==null"); } clients--; } /** * 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数 * 限制,则创建并返回新连接 * * @param name 在属性文件中定义的连接池名字 * @return Connection 可用连接或null */ public Connection getConnection(String name) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); if (pool != null) { //return pool.getConnection(); return pool.returnConnection(); } return null; } /** * 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制, * 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接. * * @param name 连接池名字 * @param time 以毫秒计的等待时间 * @return Connection 可用连接或null */ public Connection getConnection(String name, long time) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); if (pool != null) { return pool.getConnection(time); } return null; } /** * 关闭所有连接,撤销驱动程序的注册 */ public synchronized void release() { // 等待直到最后一个客户程序调用 if (--clients != 0) { return; } Enumeration allPools = pools.elements(); while (allPools.hasMoreElements()) { DBConnectionPool pool = (DBConnectionPool) allPools.nextElement(); pool.release(); } Enumeration allDrivers = drivers.elements(); while (allDrivers.hasMoreElements()) { Driver driver = (Driver) allDrivers.nextElement(); try { DriverManager.deregisterDriver(driver); log("撤销JDBC驱动程序 " + driver.getClass().getName()+"的注册"); } catch (SQLException e) { log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName()); } } } /** * 根据指定属性创建连接池实例. * * @param props 连接池属性 */ private void createPools(Properties props) { Enumeration propNames = props.propertyNames(); while (propNames.hasMoreElements()) { String name = (String) propNames.nextElement(); if (name.endsWith(".url")) { String poolName = name.substring(0, name.lastIndexOf(".")); String url = props.getProperty(poolName + ".url"); if (url == null) { log("没有为连接池" + poolName + "指定URL"); continue; } String user = props.getProperty(poolName + ".user"); String password = props.getProperty(poolName + ".password"); String maxconn = props.getProperty(poolName + ".maxconn", "0"); int max; try{ max = Integer.valueOf(maxconn).intValue(); } catch (NumberFormatException e) { log("错误的最大连接数限制: " + maxconn + " .连接池: " + poolName); max = 0; } DBConnectionPool pool = new DBConnectionPool(poolName, url, user, password, max); pools.put(poolName, pool); log("成功创建连接池" + poolName); } } } /** * 读取属性完成初始化 */ private void init() { try { Properties p = new Properties(); String configs = System.getProperty("user.dir")+"confdb.properties"; System.out.println("configs file local at "+configs); FileInputStream is = new FileInputStream(configs); Properties dbProps = new Properties(); try { dbProps.load(is); } catch (Exception e) { System.err.println("不能读取属性文件. " +"请确保db.properties在CLASSPATH指定的路径中"); return; } String logFile = dbProps.getProperty("logfile", "DBConnectionManager.log"); try{ log = new PrintWriter(new FileWriter(logFile, true), true); } catch (IOException e) { System.err.println("无法打开日志文件: " + logFile); log = new PrintWriter(System.err); } loadDrivers(dbProps); createPools(dbProps); }catch(Exception e){} } /** 171 * 装载和注册所有JDBC驱动程序 172 * 173 * @param props 属性 174 */ private void loadDrivers(Properties props) { String driverClasses = props.getProperty("drivers"); StringTokenizer st = new StringTokenizer(driverClasses); while (st.hasMoreElements()) { String driverClassName = st.nextToken().trim(); try{ Driver driver = (Driver) Class.forName(driverClassName).newInstance(); DriverManager.registerDriver(driver); drivers.addElement(driver); System.out.println(driverClassName); log("成功注册JDBC驱动程序" + driverClassName); } catch (Exception e) { log("无法注册JDBC驱动程序: " + driverClassName + ", 错误: " + e); } } } /** * 将文本信息写入日志文件 */ private void log(String msg) { log.println(new Date() + ": " + msg); } /** * 将文本信息与异常写入日志文件 */ private void log(Throwable e, String msg) { log.println(new Date() + ": " + msg); e.printStackTrace(log); } /** * 此内部类定义了一个连接池.它能够根据要求创建新连接,直到预定的最 * 大连接数为止.在返回连接给客户程序之前,它能够验证连接的有效性. */ class DBConnectionPool { //private int checkedOut; private Vector freeConnections = new Vector(); private int maxConn; private String name; private String password; private String URL; private String user; /** * 创建新的连接池 * * @param name 连接池名字 * @param URL 数据库的JDBC URL * @param user 数据库帐号,或 null * @param password 密码,或 null * @param maxConn 此连接池允许建立的最大连接数 */ public DBConnectionPool(String name, String URL, String user, String password,int maxConn) { this.name = name; this.URL = URL; this.user = user; this.password = password; this.maxConn = maxConn; } /** * 将不再使用的连接返回给连接池 * * @param con 客户程序释放的连接 */ public synchronized void freeConnection(Connection con) { // 将指定连接加入到向量末尾 try { if(con.isClosed()){System.out.println("before freeConnection con is closed");} freeConnections.addElement(con); Connection contest = (Connection) freeConnections.lastElement(); if(contest.isClosed()){System.out.println("after freeConnection contest is closed");} notifyAll(); }catch(SQLException e){System.out.println(e);} } /** * 从连接池获得一个可用连接.如没有空闲的连接且当前连接数小于最大连接 * 数限制,则创建新连接.如原来登记为可用的连接不再有效,则从向量删除之, * 然后递归调用自己以尝试新的可用连接. */ public synchronized Connection getConnection() { Connection con = null; if (freeConnections.size() > 0) { // 获取向量中第一个可用连接 con = (Connection) freeConnections.firstElement(); freeConnections.removeElementAt(0); try { if (con.isClosed()) { log("从连接池" + name+"删除一个无效连接"); System.out.println("从连接池" + name+"删除一个无效连接"); // 递归调用自己,尝试再次获取可用连接 con = getConnection(); } } catch (SQLException e) { log("从连接池" + name+"删除一个无效连接时错误"); System.out.println("从连接池" + name+"删除一个无效连接出错"); // 递归调用自己,尝试再次获取可用连接 con = getConnection(); } if(freeConnections.size()>maxConn) { System.out.println(" 删除一个溢出连接 "); releaseOne(); } } else if((maxConn == 0)||(freeConnections.size()<maxConn)) { con = newConnection(); } return con; } public synchronized Connection returnConnection() { Connection con = null; //如果闲置小于最大连接,返回一个新连接 if(freeConnections.size()<maxConn) { con = newConnection(); } //如果闲置大于最大连接,返回一个可用的旧连接 else if(freeConnections.size()>=maxConn) { con = (Connection) freeConnections.firstElement(); System.out.println(" [a 连接池可用连接数 ] : "+"[ "+freeConnections.size()+" ]"); freeConnections.removeElementAt(0); System.out.println(" [b 连接池可用连接数 ] : "+"[ "+freeConnections.size()+" ]"); try { if (con.isClosed()) { log("从连接池" + name+"删除一个无效连接"); System.out.println("从连接池" + name+"删除一个无效连接"); returnConnection(); } }catch (SQLException e) { log("从连接池" + name+"删除一个无效连接时错误"); System.out.println("从连接池" + name+"删除一个无效连接出错"); returnConnection(); } } return con; } /** * 从连接池获取可用连接.可以指定客户程序能够等待的最长时间 * 参见前一个getConnection()方法. * * @param timeout 以毫秒计的等待时间限制 */ public synchronized Connection getConnection(long timeout) { long startTime = new Date().getTime(); Connection con; while ((con = getConnection()) == null) { try { wait(timeout); } catch (InterruptedException e) {} if ((new Date().getTime() - startTime) >= timeout) { // wait()返回的原因是超时 return null; } } return con; } /** * 关闭所有连接 */ public synchronized void release() { Enumeration allConnections = freeConnections.elements(); while (allConnections.hasMoreElements()) { Connection con = (Connection) allConnections.nextElement(); try { con.close(); log("关闭连接池" + name+"中的一个连接"); } catch (SQLException e) { log(e, "无法关闭连接池" + name+"中的连接"); } } freeConnections.removeAllElements(); } /** * 关闭一个连接 */ public synchronized void releaseOne() { if(freeConnections.firstElement()!=null) { Connection con = (Connection) freeConnections.firstElement(); try { con.close(); System.out.println("关闭连接池" + name+"中的一个连接"); log("关闭连接池" + name+"中的一个连接"); } catch (SQLException e) { System.out.println("无法关闭连接池" + name+"中的一个连接"); log(e, "无法关闭连接池" + name+"中的连接"); } } else { System.out.println("releaseOne() bug......................................................."); } } /** * 创建新的连接 */ private Connection newConnection() { Connection con = null; try { if (user == null) { con = DriverManager.getConnection(URL); } else{ con = DriverManager.getConnection(URL, user, password); } log("连接池" + name+"创建一个新的连接"); } catch (SQLException e) { log(e, "无法创建下列URL的连接: " + URL); return null; } return con; } } } ================================ /** * Title: ConnectPool.java * Description: 数据库操作 * Copyright: Copyright (c) 2002/12/25 * Company: * Author : * remark : 加入指针回滚 * Version 2.0 */ import java.io.*; import com.sjky.pool.*; import java.sql.*; import java.util.*; import java.util.Date; import java.net.*; public class PoolMan extends ConnectPool { private ConnectPool connMgr; private Statement stmt; private Connection con ; private ResultSet rst; /** *对象连接初始化 * */ public Connection getPool(String name) throws Exception { try{ connMgr = ConnectPool.getInstance(); con = connMgr.getConnection(name); }catch(Exception e) { System.err.println("不能创建连接!请尝试重启应用服务器"); } return con; } /** *同以上方法,加入连接空闲等待时间 *待用方法 * */ public Connection getPool_t(String name, long time) throws Exception { try{ connMgr = ConnectPool.getInstance(); con = connMgr.getConnection(name,time); }catch(Exception e) { System.err.println("不能创建连接!"); } return con; } /** *执行查询方法1 * */ public ResultSet executeQuery(String SqlStr) throws Exception { ResultSet result = null; try { stmt = con.createStatement(); result = stmt.executeQuery(SqlStr); // here add one line by jnma 12.11 con.commit(); } catch(java.sql.SQLException e) { throw new Exception("执行查询语句出错"); } return result; } /** *执行查询方法2 * */ public ResultSet getRst(String SqlStr) throws Exception { // ResultSet result = null; try { stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); rst = stmt.executeQuery(SqlStr); // here add one line by jnma 12.11 con.commit(); } catch(java.sql.SQLException e) { throw new Exception("执行查询语句出错"); } return rst; } /** *执行更新 * */ public int Update(String SqlStr) throws Exception { int result = -1; try { stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); result = stmt.executeUpdate(SqlStr); // here add one line by jnma 12.11 con.commit(); if(result==0) System.out.println("执行delete,update,insert SQL出错"); } catch(java.sql.SQLException e) { System.err.println("执行delete,update,insert SQL出错"); } return result; } /** *执行事务处理 * */ public boolean handleTransaction(Vector SqlArray) throws Exception { boolean result = false; int ArraySize = SqlArray.size(); try { stmt = con.createStatement(); con.setAutoCommit(false); System.out.println("ArraySize is" +ArraySize); for(int i=0;i<ArraySize;i++) { System.out.println(" 开始执行语句"+(String)SqlArray.elementAt(i)); stmt.executeUpdate((String)SqlArray.elementAt(i)); System.out.println(" 执行成功"); } con.commit(); con.setAutoCommit(true) ;//必须 System.out.println("事务执行成功"); result = true; } catch(java.sql.SQLException e) { try { System.out.println(e.toString()); System.out.println("数据库操作失败"); con.rollback(); } catch(java.sql.SQLException Te) { System.err.println("事务出错回滚异常"); } } try { con.setAutoCommit(true); } catch(java.sql.SQLException e) { System.err.println("设置自动提交失败"); } return result; } /** *释放连接 * */ public void close(String name) throws Exception { try { if(stmt!=null) stmt.close(); if(con!=null) { connMgr.freeConnection(name,con); System.out.println(" [c 正在释放一个连接 ] "); } } catch(java.sql.SQLException e) { System.err.println("释放连接出错"); } } }
===========================
属性文件db.properties放在conf下
#drivers=com.inet.tds.TdsDriver #logfile=c: esin-2.1.4DBConnectPool-log.txt #test.maxconn=1000 #test.url=jdbc:inetdae:SERVER:1433?sql7=true #test.user=sa #test.password=test drivers=com.microsoft.jdbc.sqlserver.SQLServerDriver logfile=F: esin-2.1.4DBConnectPool-log.txt test.maxconn=20 test.url=jdbc:microsoft:sqlserver://192.168.0.5:1433;DatabaseName=test test.user=sa test.password=test #drivers=oracle.jdbc.driver.OracleDriver #logfile=c: esin-2.1.4DBConnectPool-log.txt #test.maxconn=100 #test.url=jdbc:oracle:thin:@192.168.0.10:1521:myhome #test.user=system #test.password=manager #mysql端3306 #drivers=org.gjt.mm.mysql.Driver #logfile=c: esin-2.1.4DBConnectPool-log.txt #test.maxconn=100 #test.url=jdbc:mysql://192.168.0.4:3306/my_test #test.user=root #test.password=system
发表评论
-
MongoDB疑难问题解决
2012-08-30 14:23 1431http://grokbase.com/t/gg/mongod ... -
mongodb复制集实战
2012-07-10 23:21 0mongod --replSet rs1 --keyFile ... -
NoSQL 建模技术(转载)
2012-07-01 12:01 1396全文译自墙外文章“ ... -
64位linux(Redhat5)安装Mysql5.5.14过程记录
2011-07-20 11:45 10120通过配置将Redhat使用CentOS的yum库。 从拖管方 ... -
C3PO Exception - CLOSE BY CLIENT
2011-04-01 17:42 2328We are running a standalone app ... -
Hibernate连接数据库超时设置autoReconnect=true
2011-02-06 09:56 10711Caused by: com.mysql.jdbc.exce ... -
MySQL federated引擎试验(转自david_yeung 的BLOG )
2011-01-10 15:25 1386如果写的不对的地方,欢迎各位提意见。可以在数据非常大的时候起到 ... -
关于数据库重复记录
2009-10-03 14:28 1121Oracle数据库 如何查找重复记录? SELECT ... -
数据库连接池的JAVA实现(第二篇)---使用JAVA中的动态代理实现数据库连接池
2009-09-07 22:34 1218作者通过使用JAVA中的动 ... -
数据库连接池的JAVA实现(第一篇)
2009-09-07 22:21 1351一个完整的连接池应用包括三个部分:DBConnectionPo ...
相关推荐
qtz40塔式起重机总体及塔身有限元分析法设计().zip
Elasticsearch是一个基于Lucene的搜索服务器
资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。
美国纽约HVAC(暖通空调)数据示例,谷歌地图数据包括:时间戳、名称、类别、地址、描述、开放网站、电话号码、开放时间、更新开放时间、评论计数、评级、主图像、评论、url、纬度、经度、地点id、国家等。 在地理位置服务(LBS)中,谷歌地图数据采集尤其受到关注,因为它提供了关于各种商业实体的详尽信息,这对于消费者和企业都有极大的价值。本篇文章将详细介绍美国纽约地区的HVAC(暖通空调)系统相关数据示例,此示例数据是通过谷歌地图抓取得到的,展示了此技术在商业和消费者领域的应用潜力。 无需外网,无需任何软件抓取谷歌地图数据:wmhuoke.com
2023-04-06-项目笔记-第四百五十五阶段-课前小分享_小分享1.坚持提交gitee 小分享2.作业中提交代码 小分享3.写代码注意代码风格 4.3.1变量的使用 4.4变量的作用域与生命周期 4.4.1局部变量的作用域 4.4.2全局变量的作用域 4.4.2.1全局变量的作用域_1 4.4.2.453局变量的作用域_453- 2025-04-01
1_实验三 扰码、卷积编码及交织.ppt
北京交通大学901软件工程导论必备知识点.pdf
内容概要:本文档总结了 MyBatis 的常见面试题,涵盖了 MyBatis 的基本概念、优缺点、适用场合、SQL 语句编写技巧、分页机制、主键生成、参数传递方式、动态 SQL、缓存机制、关联查询及接口绑定等内容。通过对这些问题的解答,帮助开发者深入理解 MyBatis 的工作原理及其在实际项目中的应用。文档不仅介绍了 MyBatis 的核心功能,还详细解释了其在不同场景下的具体实现方法,如通过 XML 或注解配置 SQL 语句、处理复杂查询、优化性能等。 适合人群:具备一定 Java 开发经验,尤其是对 MyBatis 有初步了解的研发人员,以及希望深入了解 MyBatis 框架原理和最佳实践的开发人员。 使用场景及目标:①理解 MyBatis 的核心概念和工作原理,如 SQL 映射、参数传递、结果映射等;②掌握 MyBatis 在实际项目中的应用技巧,包括 SQL 编写、分页、主键生成、关联查询等;③学习如何通过 XML 和注解配置 SQL 语句,优化 MyBatis 性能,解决实际开发中的问题。 其他说明:文档内容详尽,涵盖面广,适合用于面试准备和技术学习。建议读者在学习过程中结合实际项目进行练习,以更好地掌握 MyBatis 的使用方法和技巧。此外,文档还提供了丰富的示例代码和配置细节,帮助读者加深理解和应用。
《基于YOLOv8的智能电网设备锈蚀评估系统》(包含源码、可视化界面、完整数据集、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计
插头模具 CAD图纸.zip
资源内项目源码是来自个人的毕业设计,代码都测试ok,包含源码、数据集、可视化页面和部署说明,可产生核心指标曲线图、混淆矩阵、F1分数曲线、精确率-召回率曲线、验证集预测结果、标签分布图。都是运行成功后才上传资源,毕设答辩评审绝对信服的保底85分以上,放心下载使用,拿来就能用。包含源码、数据集、可视化页面和部署说明一站式服务,拿来就能用的绝对好资源!!! 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、大作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.txt文件,仅供学习参考, 切勿用于商业用途。
《基于YOLOv8的智慧农业水肥一体化控制系统》(包含源码、可视化界面、完整数据集、部署教程)简单部署即可运行。功能完善、操作简单,适合毕设或课程设计
python爬虫;智能切换策略,反爬检测机制
台区终端电科院送检文档
e235d-main.zip
丁祖昱:疫情对中国房地产市场影响分析及未来展望
MCP快速入门实战,详细的实战教程
YD5141SYZ后压缩式垃圾车的上装箱体设计.zip
IMG_20250401_195352.jpg
DeepSeek系列专题 DeepSeek技术溯源及前沿探索.pdf