- 浏览: 183396 次
- 性别:
- 来自: 杭州
博客专栏
-
Java技术分享
浏览量:0
文章分类
最新评论
-
masuweng:
学习了,学习了
mybatis是如何防止SQL注入的 -
somefuture:
终于知道了#$的区别
mybatis是如何防止SQL注入的 -
masuweng:
...
tomct处理请求的流程 -
zhp8341:
masuweng 写道寻求cas的更多例子, http://w ...
JUC之CAS -
臻是二哥:
java.util.concurrent包中到处都使用了CAS ...
JUC之CAS
package com.xyz.connpool; public interface IConnection { /** * 关闭当前连接 */ public void close(); /** * 销毁当前连接 */ public void destroy(); //应该具备的其他方法 }
public class Connection implements IConnection { private String name; private IConnPool connPool; public Connection(IConnPool connPool,String name){ this.connPool=connPool; this.name=name; } @Override public void close() { this.connPool.releaseConn(this); } @Override public void destroy() { System.out.println("destroy connection---"+name); } @Override public String toString() { // TODO Auto-generated method stub super.toString(); return name; } }
public interface IConnPool { /** * 获得一个可用连接,超过最大连接数时线程等待,直到有有连接释放时返回一个可用连接或者超时返回null * @param maxWaitTime * @return */ public IConnection getConn(); /** * 将释放的空闲连接加入空闲连接池 * @param conn */ public void releaseConn(IConnection conn); /** * 销毁连接池 */ public void destroy(); /** * 获取当前线程对应的连接 * @return */ public IConnection getCurrentConn(); }
import java.util.ArrayList; import java.util.List; import java.util.UUID; public class ConnPool implements IConnPool { private int initNum; private int maxNum; private int hasAlready; private long maxWaitTime; private final List<IConnection> freeConnList; private final List<IConnection> activeConnList; private static ThreadLocal<IConnection> threadLocalVar=new ThreadLocal<IConnection>(){ protected IConnection initialValue() { return null; }; }; public ConnPool(){ this.initNum=3; this.maxNum=5; this.hasAlready=0; this.maxWaitTime=1000; this.freeConnList=new ArrayList<IConnection>(maxNum); this.activeConnList=new ArrayList<IConnection>(maxNum); init(); } public ConnPool(int initNum,int maxNum,long maxWaitTime){ this.initNum=initNum; this.maxNum=maxNum; this.hasAlready=0; this.maxWaitTime=maxWaitTime; this.freeConnList=new ArrayList<IConnection>(maxNum); this.activeConnList=new ArrayList<IConnection>(maxNum); init(); } private void init(){ for(int i=0;i<this.initNum;i++){ synchronized (this) { this.freeConnList.add(new Connection(this,UUID.randomUUID().toString())); hasAlready++; } } } @Override public synchronized IConnection getConn() { IConnection conn=null; if(!this.freeConnList.isEmpty()){ conn=this.freeConnList.remove(0); if(conn!=null) threadLocalVar.set(conn);//为线程绑定连接 this.activeConnList.add(conn); return conn; } if(hasAlready<maxNum){ conn = new Connection(this,UUID.randomUUID().toString()); hasAlready++; if(conn!=null) threadLocalVar.set(conn);//为线程绑定连接 this.activeConnList.add(conn); return conn; } try { this.wait(maxWaitTime); if(!this.freeConnList.isEmpty()){ conn=this.freeConnList.remove(0); if(conn!=null) threadLocalVar.set(conn);//为线程绑定连接 this.activeConnList.add(conn); return conn; } return null; } catch (InterruptedException e) { e.printStackTrace(); return null; } } @Override public synchronized void releaseConn(IConnection conn) { if(this.activeConnList.contains(conn)){ this.freeConnList.add(conn); this.activeConnList.remove(conn); threadLocalVar.remove(); this.notify(); } } @Override public synchronized void destroy() { IConnection conn=null; int temp=this.freeConnList.size(); for(int i=0;i<temp;i++){ conn=this.freeConnList.remove(0); conn.destroy(); } temp=this.activeConnList.size(); for(int i=0;i<temp;i++){ conn=this.activeConnList.remove(0); conn.destroy(); } conn=null; this.hasAlready=0; } @Override public IConnection getCurrentConn() { return threadLocalVar.get(); } }
package com.xyz.connpool; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ConnPoolManager { private int initConnNum; private int maxConnNum; private long maxWaitTime; // 连接池存放 public Map<Integer,IConnPool> pools=new ConcurrentHashMap<Integer, IConnPool>(); // public Hashtable<Integer,IConnPool> pools = new Hashtable<Integer, IConnPool>(); public ConnPoolManager(int initConnNum,int maxConnNum, long maxWaitTime){ this.initConnNum=initConnNum; this.maxConnNum=maxConnNum; this.maxWaitTime=maxWaitTime; init(); } // 初始化所有的连接池 private void init(){ for(int hostId =0;hostId<3;hostId++){ ConnPool connPool=new ConnPool(this.initConnNum,this.maxConnNum, this.maxWaitTime); if(connPool != null){ pools.put(hostId,connPool); System.out.println("Info:Init connPool successed for hostId ->" +hostId); } } } /** * 根据主机id获取连接池 * @param hostId * @return */ public IConnPool getPool(int hostId){ IConnPool pool = null; if(pools.containsKey(hostId)){ pool = pools.get(hostId); } return pool; } /** * 获取一个到主机hostId的连接 * @param hostId * @return */ public IConnection getConn(int hostId){ IConnPool connPool = getPool(hostId); if(connPool==null){ System.out.println("Error:Can't find this connecion pool for hostId->"+hostId); return null; } return connPool.getConn(); } /** * 关闭指定主机的某个链接 * @param hostId * @param conn */ public void close(int hostId,IConnection conn){ IConnPool pool = getPool(hostId); if(pool != null) pool.releaseConn(conn); } /** * 注销某个主机的连接池 * @param poolName */ public void destroy(int hostId){ IConnPool pool = getPool(hostId); if(pool != null){ pool.destroy(); } pools.remove(pool); } /** * 注销所有连接池 */ public void destory(){ for(int hostId:pools.keySet()){ this.destroy(hostId); } } }
package com.xyz.connpool; import java.util.concurrent.CountDownLatch; public class Demo { public final static int REQUESTNUM=200; public final static int DURATION=20; public static void main(String [] args) throws Exception{ final CountDownLatch startGate=new CountDownLatch(1); final CountDownLatch endGate=new CountDownLatch(REQUESTNUM); final ConnPoolManager cpm=new ConnPoolManager(5, 10, 1000); final IConnection conns[] =new IConnection[REQUESTNUM]; for(int i=0;i<REQUESTNUM;i++){ final int flag=i; new Thread(new Runnable() { @Override public void run() { try { startGate.await(); } catch (InterruptedException e1) {} conns[flag]=cpm.getConn(0); System.out.println(conns[flag]); try { Thread.sleep(DURATION); } catch (InterruptedException e) {} cpm.close(0, conns[flag]); endGate.countDown(); } }).start(); } long begin = System.currentTimeMillis(); startGate.countDown(); endGate.await(); long over = System.currentTimeMillis(); System.out.println(over-begin); // Thread.sleep(5000); cpm.destory(); } }
源代码下载https://github.com/ZhenShiErGe/ConnectionPool.git
发表评论
-
精心准备的讲解Java多线程的知乎Live
2018-09-02 21:39 704花了一个月的时间,结合自己的理解,制作了一个以图片的方式讲解J ... -
在知乎推出Java求职类专栏文章
2018-08-27 12:06 790从昨天起,笔者开始在知乎推出Java求职类专栏文章,主要涉及一 ... -
JUC之AQS
2016-07-27 15:49 1205AQS是同步框架,它进行 ... -
JUC之CAS
2016-07-27 10:56 1557JUC是java.util.concurrent包 ... -
JAVA并发-线程状态和线程组
2016-07-18 14:14 1267在Java中,线程有6种基本状态,理解这6种基本状态之间的关系 ... -
JAVA并发-条件队列
2016-07-02 09:57 1115在JVM系列博客http://yizhen ... -
JAVA并发-中断处理和任务取消
2016-06-27 22:42 1196中断处理 在java程序中 ... -
JAVA并发-显式锁(二)
2016-06-06 09:25 1024在上一篇博客《JAVA并发-显式锁(一)》中介绍了Lock和R ... -
JAVA并发-显式锁(一)
2016-06-05 20:40 891JAVA语言除了提供内置锁synchronized,还在JDK ... -
JAVA并发-减少锁的竞争
2016-06-04 16:01 1846降低锁的竞争可以提高 ... -
JAVA并发-3种典型的死锁
2016-06-03 19:54 1621在JAVA并发编程中,我们 ... -
JAVA并发-3种典型的死锁
2016-06-03 10:02 10在JAVA并发编程中,我们 ... -
JAVA并发-ThreadPoolExecutor线程池的使用
2016-05-30 16:19 2356在博客JAVA并发-Executor任务执行框架中曾说过,Ex ... -
JAVA并发-Executor任务执行框架
2016-05-27 19:10 432首先介绍两个重要的接 ... -
JAVA并发-DCL与JMM
2016-04-26 19:21 1568首先必须声明,在volatil ... -
JAVA并发-构建可靠的结果缓存
2016-04-10 16:58 55在学习了前面关于多线程的博客之后,下面来介绍一个构建可靠结果缓 ... -
JAVA并发-并发编程常用类
2016-04-08 11:07 991在讲同步工具类之前,笔者想先介绍一下Runnable,Call ... -
JAVA并发-同步容器和并发容器
2016-04-07 19:02 698常见的同步容器类包括V ... -
JAVA并发-开发线程安全类
2016-04-01 10:23 840我们知道,面向对象的 ... -
JAVA并发-为现有的线程安全类添加原子方法
2016-03-30 20:46 1390JAVA中有许多线程安全的基础模块类,一般情况下,这些基础模块 ...
相关推荐
百度云盘分享 ... Java实现的FTP连接与数据浏览程序,实现实例化可操作的窗口。 部分源代码摘录: ftpClient = new FtpClient(); //实例化FtpClient对象 String serverAddr=jtfServer.getText();...
Java实现的FTP连接与数据浏览程序,实现实例化可操作的窗口。 部分源代码摘录: ftpClient = new FtpClient(); //实例化FtpClient对象 String serverAddr=jtfServer.getText(); //得到服务器地址 ...
Java程序.............................................................................................6 1.3.1 Java程序的结构 ...........................................................................
主要包括JDBC的基本应用开发、传统数据库连接池技术的应用、流行的druid数据库连接池、数据库事务和并发控制、应用程序典型三层架构和DAO层的封装以及最后运用三层架构的框架进行JDBC的综合应用。从零讲起,实战为主...
为了增加系统的吞吐量,提高并发处理客户请求数量,系统采用了IBM服务器作为主机。在数据库处理方面,不需要在数据层借助存储过程及数据库服务器端函数封装过多的业务逻辑,因此数据库系统采用相对精巧的MySQL[6]。...
使用ibatis 提供的ORM 机制,对业务逻辑实现人员而言,面对的是纯粹的Java 对象, 这一层与通过Hibernate 实现ORM 而言基本一致,而对于具体的数据操作,Hibernate 会自动生成SQL 语句,而ibatis 则要求...
GoF 的《设计模式》是所有面向对象语言(C++ Java C#)的基础,只不过不同的语言将之实现得更方便地使用。 GOF 的设计模式是一座"桥" 就 Java 语言体系来说,GOF 的设计模式是 Java 基础知识和 J2EE 框架知识之间一...
说明:用于连接到oracle数据库,也可实现用户的切换 用法:conn 用户名/密码 [as sysdba/sysoper] 注意:当用特权用户连接时,必须带上sysdba或sysoper 例子: 3. 断开连接(disc) 说明:断开与当前数据库的连接 ...