`
komei
  • 浏览: 89594 次
  • 性别: 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的开发。

    Mysql 教程(Markd格式 经典全面 看这一个资料就够了)

    Mysql 教程(Markd格式 经典全面 看这一个资料就够了)涵盖了mysql工作流、事务、锁、索引、性能优化、运维和配置等各个方面。

    pyzmq-25.1.0-cp36-cp36m-musllinux_1_1_i686.whl

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

    my-tv-v2.1.2.apk

    电视剧里面了

    debugpy-1.6.2-cp39-cp39-macosx_10_15_x86_64.whl

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

    泛微OAE10,E-Builder零代码应用构建平台操作手册

    泛微OAE10,E-Builder零代码应用构建平台操作手册

    布尔诺理工大学的VHDL课程

    布尔诺理工大学(Brno University of Technology, BUT)提供的 VHDL(硬件描述语言)课程是计算机工程和电子工程学科的重要组成部分,专注于数字系统设计和实现。该课程旨在为学生提供 VHDL 的基础知识和实用技能,使他们能够设计、模拟和实现复杂的数字电路。 ### **课程概述** **课程目标** - **掌握 VHDL 基础**:理解 VHDL 的语法、结构和基本概念,包括信号、变量、过程、函数和实体。 - **学习数字设计技术**:使用 VHDL 描述、设计和验证组合逻辑、时序电路和复杂的数字系统。 - **掌握建模和仿真**:学习如何通过 VHDL 对数字系统进行建模,并使用仿真工具进行验证。 - **硬件实现能力**:通过编译 VHDL 代码,在 FPGA 等硬件平台上进行综合与实现。 **课程内容** - **VHDL 语言基础**:介绍 VHDL 的基本语法,包括数据类型、运算符和控制结构。 - **结构化设计**:讲解如何使用 VHDL 进行层次化设计,模块化设计,以及组件实例化。 - **组合逻辑电路**:学习如何用 VHDL 描述

    docker SWARM 部署教程

    docker SWARM 部署教程

    pyzmq-25.0.2-cp39-cp39-musllinux_1_1_x86_64.whl

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

    同城拼车(完整带PHP后台)

    同城拼车(完整带PHP后台)

    cryptography-2.6.1-cp34-abi3-macosx_10_6_intel.whl

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

    基于PHP+MySQL+Ajax实现的在线二手书交易平台+源代码+详细文档

    php 基于PHP+MySQL+Ajax实现的在线二手书交易平台+源代码+详细文档

    redis升级和部署6.2.6最新稳定版文档和程序

    redis升级和部署6.2.6最新稳定版文档和程序.zipredis升级和部署6.2.6最新稳定版文档和程序.zipredis升级和部署6.2.6最新稳定版文档和程序.zipredis升级和部署6.2.6最新稳定版文档和程序.zipredis升级和部署6.2.6最新稳定版文档和程序.zipredis升级和部署6.2.6最新稳定版文档和程序.zipredis升级和部署6.2.6最新稳定版文档和程序.zipredis升级和部署6.2.6最新稳定版文档和程序.zipredis升级和部署6.2.6最新稳定版文档和程序.zipredis升级和部署6.2.6最新稳定版文档和程序.zip

    03钢筋锥螺纹连接工程.doc

    03钢筋锥螺纹连接工程

    154653668719337b站.apk

    154653668719337b站.apk

    ipython-0.7.3-py2.5.egg

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

    基于ssm框架网上花店系统毕业论文

    摘 要 网络技术和计算机技术发展至今,已经拥有了深厚的理论基础,并在现实中进行了充分运用,尤其是基于计算机运行的软件更是受到各界的关注。加上现在人们已经步入信息时代,所以对于信息的宣传和管理就很关键。因此鲜花销售信息的管理计算机化,系统化是必要的。设计开发网上花店不仅会节约人力和管理成本,还会安全保存庞大的数据量,对于鲜花销售信息的维护和检索也不需要花费很多时间,非常的便利。 网上花店是在MySQL中建立数据表保存信息,运用SSM+Vue框架和Java语言编写。并按照软件设计开发流程进行设计实现。系统具备友好性且功能完善。管理员登录进入本人后台之后,主要完成花材选择管理,用户管理,鲜花管理,鲜花出入库管理,鲜花订单管理等。用户联系客服咨询问题,查看鲜花,可以收藏,购买,评论鲜花,支付订单,管理个人订单等。 网上花店在让鲜花销售信息规范化的同时,也能及时通过数据输入的有效性规则检测出错误数据,让数据的录入达到准确性的目的,进而提升网上花店提供的数据的可靠性,让系统数据的错误率降至最低。 关键词:网上花店;MySQL;SSM+Vue框架

    grpcio-1.22.0-cp36-cp36m-win_amd64.whl

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

    20230626-汽车行业大国重车之琰究智能汽车系列报告七-智能驾驶,三重拐点临近,L3落地加速-华西证券-49页.pdf

    20230626-汽车行业大国重车之琰究智能汽车系列报告七-智能驾驶,三重拐点临近,L3落地加速-华西证券-49页.pdf

    若依(ruoyi)社区系统源代码共享共学

    一个前后端完整系统,包括基本的模块管理、数据管理等,代码完整,可读性高,适合初学者练手,也可以基于这个框架自己添减改动,完成其他功能。本框架是从若依官网上下载得来,为便捷用,各种问题请留言,看到一定回复。

Global site tag (gtag.js) - Google Analytics