连接池的基本实现
来源:互联网 发布:山东大学继续网络教育 编辑:程序博客网 时间:2024/04/27 15:55
对于池的概念,大家都不陌生,储存昂贵的资源,比如线程,jdbc连接,线程池有现成的,这里就不献丑了,主要写下连接池吧
连接池类
public class ConnectionPool {private static volatile ConnectionPool connPool;private static final String url = "jdbc:mysql://localhost:3306/java? user=root&password=root&useUnicode=true&characterEncoding=UTF8";private final List<Connection> list = new ArrayList<Connection>();private final PoolState poolState = new PoolState();private int totalConnect;private ConnectionPool(){}static{ try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {e.printStackTrace();}}public static ConnectionPool getInstance(){if(connPool == null){synchronized (ConnectionPool.class) {if(connPool == null){connPool = new ConnectionPool();}}}return connPool;}public synchronized Connection getConnection() throws Exception{int idleConnectCount = list.size();poolState.setIdleConnectCount(idleConnectCount);if(idleConnectCount == 0 && totalConnect != 10){ return createConnection();}else if(idleConnectCount != 0){Connection connection = list.get(0);list.remove(0);return connection;}else{throw new Exception("pool is full and connect all use");}}private Connection createConnection(){Connection connection = null;try {connection = DriverManager.getConnection(url);totalConnect++;} catch (SQLException e) {e.printStackTrace();}return connection;}public synchronized void release(Connection connection){//1000毫秒if(poolState.getIdleWorkCount(1000) > 0){try {connection.close();//销毁连接totalConnect--;} catch (SQLException e) {e.printStackTrace();}}else{//缓存连接list.add(connection);}}}
连接状态类
package com.wangliyong.tool.connpool;public class PoolState {private long duration;private int idleConnectCount;public void setIdleConnectCount(int idleConnectCount) {if(this.idleConnectCount <=2 && idleConnectCount > 2){duration = System.currentTimeMillis();}this.idleConnectCount = idleConnectCount;}public int getIdleWorkCount(long duration) {if ((System.currentTimeMillis() - this.duration > duration)) {return (idleConnectCount - 2);}return 0;}}
0 0
- 连接池的基本实现
- 数据连接池的基本实现
- 连接池的基本工作原理和实现
- DBCP与C3P0连接池以及基本分页的实现
- JDBC学习之路(十)编写一个基本的连接池来实现连接的复用
- 连接池的实现
- java连接MySQL数据库及实现基本的增查
- 连接池的基本工作原理
- 连接池的基本工作原理
- Java连接池的基本工作原理
- 连接池的基本工作原理
- Java连接池的基本工作原理
- Java连接池的基本工作原理
- 连接池的基本工作原理
- Java连接池的基本工作原理
- Java连接池的基本工作原理
- c3p0--Jdbc连接池的基本使用
- 连接池的基本工作原理
- Sublime 插件实现。
- Mac mysql tar格式 安装
- MongoEngine中文参考
- C代码在GCC编译器下不需要函数前置声明
- c 【NOIP2017GDKOI模拟1.12】
- 连接池的基本实现
- 搜集的 jetson. tx1 优点
- java服务器获得客户端IP地址
- TypeScript学习笔记之 接口(Interface)
- 17 - 03 - 22 图解HTTP(26)
- 传说中的Q_PROPERTY怎么使用
- echarts3 series.data数据格式备忘
- 使用jquery.qrcode生成二维码
- 15 个 Android 通用流行框架大全