`
komei
  • 浏览: 89584 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

MiniConnectionPoolManager

阅读更多
import java.util.concurrent.Semaphore;
import java.util.Stack;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.PooledConnection;

/**
 * A simple standalone JDBC connection pool manager.
 * <p>
 * The public methods of this class are thread-safe.
 * <p>
 * Author: Christian d'Heureuse (<a
 * href="http://www.source-code.biz">www.source-code.biz</a>)<br>
 * License: <a href="http://www.gnu.org/licenses/lgpl.html">LGPL</a>.
 * <p>
 * 2007-06-21: Constructor with a timeout parameter added.
 */
public class MiniConnectionPoolManager {

private ConnectionPoolDataSource       dataSource;
private int                            maxConnections;
private int                            timeout;
private PrintWriter                    logWriter;
private Semaphore                      semaphore;
private Stack<PooledConnection>        recycledConnections;
private int                            activeConnections;
private PoolConnectionEventListener    poolConnectionEventListener;
private boolean                        isDisposed;

/**
 * Thrown in {@link #getConnection()} when no free connection becomes available
 * within <code>timeout</code> seconds.
 */
public static class TimeoutException extends RuntimeException {
   private static final long serialVersionUID = 1;
   public TimeoutException () {
      super ("Timeout while waiting for a free database connection."); }}

/**
 * Constructs a MiniConnectionPoolManager object with a timeout of 60 seconds.
 *
 * @param dataSource
 *            the data source for the connections.
 * @param maxConnections
 *            the maximum number of connections.
 */
public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections) {
   this (dataSource, maxConnections, 60); }

/**
 * Constructs a MiniConnectionPoolManager object.
 *
 * @param dataSource
 *            the data source for the connections.
 * @param maxConnections
 *            the maximum number of connections.
 * @param timeout
 *            the maximum time in seconds to wait for a free connection.
 */
public MiniConnectionPoolManager (ConnectionPoolDataSource dataSource, int maxConnections, int timeout) {
   this.dataSource = dataSource;
   this.maxConnections = maxConnections;
   this.timeout = timeout;
   try {
      logWriter = dataSource.getLogWriter(); }
    catch (SQLException e) {}
   if (maxConnections < 1) throw new IllegalArgumentException("Invalid maxConnections value.");
   semaphore = new Semaphore(maxConnections,true);
   recycledConnections = new Stack<PooledConnection>();
   poolConnectionEventListener = new PoolConnectionEventListener(); }

/**
 * Closes all unused pooled connections.
 */
public synchronized void dispose() throws SQLException {
   if (isDisposed) return;
   isDisposed = true;
   SQLException e = null;
   while (!recycledConnections.isEmpty()) {
      PooledConnection pconn = recycledConnections.pop();
      try {
         pconn.close(); }
       catch (SQLException e2) {
          if (e == null) e = e2; }}
   if (e != null) throw e; }

/**
 * Retrieves a connection from the connection pool. If
 * <code>maxConnections</code> connections are already in use, the method
 * waits until a connection becomes available or <code>timeout</code> seconds
 * elapsed. When the application is finished using the connection, it must close
 * it in order to return it to the pool.
 *
 * @return a new Connection object.
 * @throws TimeoutException
 *             when no connection becomes available within <code>timeout</code>
 *             seconds.
 */
public Connection getConnection() throws SQLException {
   // This routine is unsynchronized, because semaphore.acquire() may block.
   synchronized (this) {
      if (isDisposed) throw new IllegalStateException("Connection pool has been disposed."); }
   try {
      if (!semaphore.tryAcquire(timeout,TimeUnit.SECONDS))
         throw new TimeoutException(); }
    catch (InterruptedException e) {
      throw new RuntimeException("Interrupted while waiting for a database connection.",e); }
   boolean ok = false;
   try {
      Connection conn = getConnection2();
      ok = true;
      return conn; }
    finally {
      if (!ok) semaphore.release(); }}

private synchronized Connection getConnection2() throws SQLException {
   if (isDisposed) throw new IllegalStateException("Connection pool has been disposed.");   // test
                                                                                            // again
                                                                                            // with
                                                                                            // lock
   PooledConnection pconn;
   if (!recycledConnections.empty()) {
      pconn = recycledConnections.pop(); }
    else {
      pconn = dataSource.getPooledConnection(); }
   Connection conn = pconn.getConnection();
   activeConnections++;
   pconn.addConnectionEventListener (poolConnectionEventListener);
   assertInnerState();
   return conn; }

private synchronized void recycleConnection (PooledConnection pconn) {
   if (isDisposed) { disposeConnection (pconn); return; }
   if (activeConnections <= 0) throw new AssertionError();
   activeConnections--;
   semaphore.release();
   recycledConnections.push (pconn);
   assertInnerState(); }

private synchronized void disposeConnection (PooledConnection pconn) {
   if (activeConnections <= 0) throw new AssertionError();
   activeConnections--;
   semaphore.release();
   closeConnectionNoEx (pconn);
   assertInnerState(); }

private void closeConnectionNoEx (PooledConnection pconn) {
   try {
      pconn.close(); }
    catch (SQLException e) {
      log ("Error while closing database connection: "+e.toString()); }}

private void log (String msg) {
   String s = "MiniConnectionPoolManager: "+msg;
   try {
      if (logWriter == null)
         System.err.println (s);
       else
         logWriter.println (s); }
    catch (Exception e) {}}

private void assertInnerState() {
   if (activeConnections < 0) throw new AssertionError();
   if (activeConnections+recycledConnections.size() > maxConnections) throw new AssertionError();
   if (activeConnections+semaphore.availablePermits() > maxConnections) throw new AssertionError(); }

private class PoolConnectionEventListener implements ConnectionEventListener {
   public void connectionClosed (ConnectionEvent event) {
      PooledConnection pconn = (PooledConnection)event.getSource();
      pconn.removeConnectionEventListener (this);
      recycleConnection (pconn); }
   public void connectionErrorOccurred(ConnectionEvent event) {
      PooledConnection pconn = (PooledConnection)event.getSource();
      pconn.removeConnectionEventListener (this);
      disposeConnection (pconn); }}

/**
 * Returns the number of active (open) connections of this pool. This is the
 * number of <code>Connection</code> objects that have been issued by
 * {@link #getConnection()} for which <code>Connection.close()</code> has not
 * yet been called.
 *
 * @return the number of active connections.
 */
public synchronized int getActiveConnections() {
   return activeConnections; }

} // end class MiniConnectionPoolManager







// Test program for the MiniConnectionPoolManager class.

import java.io.PrintWriter;
import java.lang.Thread;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
import javax.sql.ConnectionPoolDataSource;

import com.oval.research.connpool.MiniConnectionPoolManager;

public class TestMiniConnectionPoolManager {

    private static final int maxConnections = 8; // number of connections

    private static final int noOfThreads = 50; // number of worker threads

    private static final int processingTime = 30; // total processing time of
                                                    // the test program in
                                                    // seconds

    private static final int threadPauseTime1 = 100; // max. thread pause
                                                        // time in microseconds,
                                                        // without a connection

    private static final int threadPauseTime2 = 100; // max. thread pause
                                                        // time in microseconds,
                                                        // with a connection

    private static MiniConnectionPoolManager poolMgr;

    private static WorkerThread[] threads;

    private static boolean shutdownFlag;

    private static Object shutdownObj = new Object();

    private static Random random = new Random();

    private static class WorkerThread extends Thread {
        public int threadNo;

        public void run() {
            threadMain(threadNo);
        }
    };

    private static ConnectionPoolDataSource createDataSource() throws Exception {

        // Version for H2:
        /*
         * org.h2.jdbcx.JdbcDataSource dataSource = new
         * org.h2.jdbcx.JdbcDataSource(); dataSource.setURL
         * ("jdbc:h2:file:c:/temp/temp_TestMiniConnectionPoolManagerDB;DB_CLOSE_DELAY=-1");
         */
        // Version for Apache Derby:
        org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource dataSource = new org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource();
        dataSource
                .setDatabaseName("e:/mimiConnection/temp_TestMiniConnectionPoolManagerDB");
        dataSource.setCreateDatabase("create");
        dataSource.setLogWriter(new PrintWriter(System.out));

        // Versioo for JTDS:
        /*
         * net.sourceforge.jtds.jdbcx.JtdsDataSource dataSource = new
         * net.sourceforge.jtds.jdbcx.JtdsDataSource(); dataSource.setAppName
         * ("TestMiniConnectionPoolManager"); dataSource.setDatabaseName
         * ("Northwind"); dataSource.setServerName ("localhost");
         * dataSource.setUser ("sa"); dataSource.setPassword
         * (System.getProperty("saPassword"));
         */

        // Version for the Microsoft SQL Server driver (sqljdbc.jar):
        /*
         * // The sqljdbc 1.1 documentation, chapter "Using Connection Pooling",
         * recommends to use // SQLServerXADataSource instead of
         * SQLServerConnectionPoolDataSource, even when no // distributed
         * transactions are used.
         * com.microsoft.sqlserver.jdbc.SQLServerXADataSource dataSource = new
         * com.microsoft.sqlserver.jdbc.SQLServerXADataSource();
         * dataSource.setApplicationName ("TestMiniConnectionPoolManager");
         * dataSource.setDatabaseName ("Northwind"); dataSource.setServerName
         * ("localhost"); dataSource.setUser ("sa"); dataSource.setPassword
         * (System.getProperty("saPassword")); dataSource.setLogWriter (new
         * PrintWriter(System.out));
         */

        return dataSource;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("Program started.");
        ConnectionPoolDataSource dataSource = createDataSource();
        poolMgr = new MiniConnectionPoolManager(dataSource, maxConnections);
        initDb();
        startWorkerThreads();
        pause(processingTime * 1000000);
        System.out.println("\nStopping threads.");
        stopWorkerThreads();
        System.out.println("\nAll threads stopped.");
        poolMgr.dispose();
        System.out.println("Program completed.");
    }

    private static void startWorkerThreads() {
        threads = new WorkerThread[noOfThreads];
        for (int threadNo = 0; threadNo < noOfThreads; threadNo++) {
            WorkerThread thread = new WorkerThread();
            threads[threadNo] = thread;
            thread.threadNo = threadNo;
            thread.start();
        }
    }

    private static void stopWorkerThreads() throws Exception {
        setShutdownFlag();
        for (int threadNo = 0; threadNo < noOfThreads; threadNo++) {
            threads[threadNo].join();
        }
    }

    private static void setShutdownFlag() {
        synchronized (shutdownObj) {
            shutdownFlag = true;
            shutdownObj.notifyAll();
        }
    }

    private static void threadMain(int threadNo) {
        try {
            threadMain2(threadNo);
        } catch (Throwable e) {
            System.out.println("\nException in thread " + threadNo + ": " + e);
            e.printStackTrace(System.out);
            setShutdownFlag();
        }
    }

    private static void threadMain2(int threadNo) throws Exception {
        // System.out.println ("Thread "+threadNo+" started.");
        while (true) {
            if (!pauseRandom(threadPauseTime1))
                return;
            threadTask(threadNo);
        }
    }

    private static void threadTask(int threadNo) throws Exception {
        Connection conn = null;
        try {
            conn = poolMgr.getConnection();
            if (shutdownFlag)
                return;
            System.out.print(threadNo + " ");
            incrementThreadCounter(conn, threadNo);
            pauseRandom(threadPauseTime2);
        } finally {
            if (conn != null)
                conn.close();
        }
    }

    private static boolean pauseRandom(int maxPauseTime) throws Exception {
        return pause(random.nextInt(maxPauseTime));
    }

    private static boolean pause(int pauseTime) throws Exception {
        synchronized (shutdownObj) {
            if (shutdownFlag)
                return false;
            if (pauseTime <= 0)
                return true;
            int ms = pauseTime / 1000;
            int ns = (pauseTime % 1000) * 1000;
            shutdownObj.wait(ms, ns);
        }
        return true;
    }

    private static void initDb() throws SQLException {
        Connection conn = null;
        try {
            conn = poolMgr.getConnection();
            System.out.println("initDb connected");
            initDb2(conn);
        } finally {
            if (conn != null)
                conn.close();
        }
        System.out.println("initDb done");
    }

    private static void initDb2(Connection conn) throws SQLException {
        execSqlNoErr(conn, "drop table temp");
        execSql(conn, "create table temp (threadNo integer, ctr integer)");
        for (int i = 0; i < noOfThreads; i++)
            execSql(conn, "insert into temp values(" + i + ",0)");
    }

    private static void incrementThreadCounter(Connection conn, int threadNo)
            throws SQLException {
        execSql(conn, "update temp set ctr = ctr + 1 where threadNo="
                + threadNo);
    }

    private static void execSqlNoErr(Connection conn, String sql) {
        try {
            execSql(conn, sql);
        } catch (SQLException e) {
        }
    }

    private static void execSql(Connection conn, String sql)
            throws SQLException {
        Statement st = null;
        try {
            st = conn.createStatement();
            st.executeUpdate(sql);
        } finally {
            if (st != null)
                st.close();
        }
    }

} // end class TestMiniConnectionPoolManager
分享到:
评论

相关推荐

    miniConnectionPoolManager.zip

    一个简单轻量的连接池,能够实现jdbc连接的基本管理,可以自己封装一个jdbc的开发组件用于jdbc的开发。

    哈尔滨工程大学833社会研究方法2020考研专业课初试大纲.pdf

    哈尔滨工程大学考研初试大纲

    基于ASP酒店房间预约系统(源代码+论文)【ASP】.zip

    基于ASP酒店房间预约系统(源代码+论文)【ASP】

    毕业设计基于机器学习的DDoS入侵检测python源码+设计文档.zip

    毕业设计基于机器学习的DDoS入侵检测python源码(高分项目).zip个人经导师指导并认可通过的高分毕业设计项目,评审分98分。主要针对计算机相关专业的正在做毕设的学生和需要项目实战练习的学习者,也可作为课程设计、期末大作业。

    NewNormal.txt

    NewNormal

    re2-0.2.14.tar.gz

    Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。

    哈尔滨工程大学《常微分方程》2020考研专业课复试大纲.pdf

    哈尔滨工程大学考研复试大纲

    grpcio-1.14.0-cp35-cp35m-macosx_10_7_intel.whl

    Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。

    哈尔滨工程大学《化工原理》2020考研专业课复试大纲.pdf

    哈尔滨工程大学考研复试大纲

    基于 STM32 U575 芯片组

    头 microSWIFT V2 固件,基于 STM32 U575 芯片组。作为项目导入到STM32CubeIDE中

    bailando 网络 smpl pkl 数据+ blendershape csv数据集训练代码

    bailando 网络 smpl pkl 数据+ blendershape csv数据集训练代码

    cryptography-2.0-cp34-cp34m-manylinux1_x86_64.whl

    Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。

    Arthas测试使用-ThreadDeadLock代码

    Arthas测试使用

    re2-0.2.21.tar.gz

    Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。

    基于Java的基于流媒体的vod视频点播网(源码+论文+需求分析+数据库文件+演示视频).zip

    本系统最大的特点是使用操作简单、友好的提示信息。本系统将实现以下基本功能: (1) 系统具有简洁大方的页面,使用简便,友好的错误操作提示 (2) 管理员用户具有系统信息管理、班级信息管理、教师信息管理、学生信息管理、公告管理、留言管理、资料管理、点播视频管理等功能。 (3) 具有较强的安全性,避免用户的恶意操作 本基于Web技术的B/S结构的系统采用jsp技术进行开发设计,开发环境是MyEclipse,服务器采用tomcat,通过jdbc驱动和数据库进行无缝连接,具有较高的完整性,一致性和安全性。

    基于Python+PyQt5的网上书店管理系统源码+项目说明(含登录功能+课设报告).zip

    基于Python+PyQt5的网上书店管理系统源码+项目说明(含登录功能+课设报告).zip 基于Python+PyQt5的网上书店管理系统源码+项目说明(含登录功能+课设报告).zip 基于Python+PyQt5的网上书店管理系统源码+项目说明(含登录功能+课设报告).zip 【优质项目推荐】 1.项目代码功能经验证ok,确保稳定可靠运行。欢迎下载使用!在使用过程中,如有问题或建议,请及时私信沟通,帮助解答。 2.项目主要针对各个计算机相关专业,包括计科、信息安全、数据科学与大数据技术、人工智能、通信、物联网等领域的在校学生、专业教师或企业员工使用。 3.项目具有丰富的拓展空间,不仅可作为入门进阶,也可直接作为毕设、课程设计、大作业、项目初期立项演示等用途。 4.如果基础还行,或热爱钻研,可基于此项目进行二次开发,DIY其他不同功能。 基于Python+PyQt5的网上书店管理系统源码+项目说明(含登录功能+课设报告).zip 功能 - 智能检查:检查书店存在此图书以及电话号码是否合法 - 采用下拉框智能补全,通过出售书名来补全,作者信息栏,通过出售书名来补全出版社,以确保书名,作者,出版社一一对应;通过买方手机号来补全默认配送地址,配送地址可随改 - 智能提示:提示书名与电话号码填写问题 - 第二遍确认 ### 修改图书页 ![](https://gowi-picgo.oss-cn-shenzhen.aliyuncs.com/picgo/20200607204627.png) 功能: - 修改图书信息(按下修改,使其一行可以修改,其余行不可修改,且不同行按钮处于冻结状态,按下完成按钮修改内容同步至数据库) - 翻页 - 返回上一级 - 查询 ### 查看会员信息 ![](https://gowi-picgo.oss-cn-shenzhen.aliyuncs.com/picgo/20200607205033.png) 功能: - 不可编辑 - 分页 - 查询 - 返回主页 ### 查看购买记录 ![](https://gowi-picgo.oss-cn-shenzhen.aliyuncs.com/picgo/20200607205146.png) 功能 - 查询 - 分页 - 按时间排序 - 不可编辑

    华为OD机试(A卷+B卷+C卷+D卷)2024真题目录(全、新、准)

    2024版华为OD机试题库,包含C、D卷所有真题,粉丝可领取体验卡免费看题,包含面试手撕代码等等内容

    平台通过测量手簿批量制作外业记录表

    铁路工程管理平台通过测量手簿批量转外业记录表,生成之后通过wps js宏批量应用样式

    基于协同过滤的就业信息分析及个性化推荐微信小程序+源代码+文档说明

    - 不懂运行,下载完可以私聊问,可远程教学 该资源内项目源码是个人的毕设,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! <项目介绍> 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。 --------

    基于C语言+stm32和esp8266通过点灯科技实现的智能台灯设计系统+源码+设计思维导图+PCB设计(毕业设计&课程设计)

    基于C语言+stm32和esp8266通过点灯科技实现的智能台灯设计系统+源码+设计思维导图+PCB设计,适合毕业设计、课程设计、项目开发。项目源码已经过严格测试,可以放心参考并在此基础上延申使用~ 基于C语言+stm32和esp8266通过点灯科技实现的智能台灯设计系统+源码+设计思维导图+PCB设计,适合毕业设计、课程设计、项目开发。项目源码已经过严格测试,可以放心参考并在此基础上延申使用~ 基于C语言+stm32和esp8266通过点灯科技实现的智能台灯设计系统+源码+设计思维导图+PCB设计,适合毕业设计、课程设计、项目开发。项目源码已经过严格测试,可以放心参考并在此基础上延申使用~ 项目简介: 使用stm32和esp8266通过点灯科技实现的智能台灯设计。 硬件平台:STM32 + ESP8266 + BH1750 + OLED12864 + W25Q64 ; 使用STM32接收esp8266的串口数据。 ESP8266接入BLINKER平台,控制数据传输。 通过PWM控制RGB 和白光,黄光的亮度开关等数据。

Global site tag (gtag.js) - Google Analytics