`
komei
  • 浏览: 91017 次
  • 性别: 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

    迷你连接池管理器(MiniConnectionPoolManager)是一个小型且轻量级的数据库连接池实现,专为简化JDBC连接管理而设计。它提供了一种有效的方式,以优化数据库访问性能和资源利用,尤其是在多线程环境中。连接池是...

    Java连接池评估报告

    6. **DbConnectionBroker** 和 **MiniConnectionPoolManager**:这两种轻量级连接池实现相对简单,适用于对性能要求不高的应用场景。 #### 四、连接池的技术特点 1. **API设计**: - DBCP和C3P0因其广泛的使用而...

    Java-ConnectionPools.rar_连接池

    7. **MiniConnectionPoolManager**:这是Apache Commons DBCP项目的一部分,它是一个简单的连接池管理器,适用于小型应用。它提供了基本的连接池管理功能,如连接初始化、最大连接限制等。 8. **Proxool_0.9.1**:...

    数据库连接池以及hibernate对各种连接池的整合

    9. **MiniConnectionPoolManager**:轻量级且无第三方依赖的JDBC数据库连接池,适用于简单场景。 10. **BoneCP**:快速且开源的连接池,比C3P0和DBCP快25倍,适合性能敏感的应用。 在配置Hibernate与连接池的整合...

    PHP语言基础知识详解及常见功能应用.docx

    本文详细介绍了PHP的基本语法、变量类型、运算符号以及文件上传和发邮件功能的实现方法,适合初学者了解和掌握PHP的基础知识。

    公司金融课程期末考试题目

    公司金融整理的word文档

    适用于 Python 应用程序的 Prometheus 检测库.zip

    Prometheus Python客户端Prometheus的官方 Python 客户端。安装pip install prometheus-client这个包可以在PyPI上找到。文档文档可在https://prometheus.github.io/client_python上找到。链接发布发布页面显示项目的历史记录并充当变更日志。吡啶甲酸

    DFC力控系统维护及使用

    DFC力控系统维护及使用

    Spring Data的书籍项目,含多数据库相关内容.zip

    1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。

    2019-2023GESP,CSP,NOIP真题.zip

    2019-2023GESP,CSP,NOIP真题.zip

    基于 Gin + Element 实现的春联生成平台

    博文链接 https://blog.csdn.net/weixin_47560078/article/details/127712877?spm=1001.2014.3001.5502

    zetero7实测可用插件

    包含: 1、jasminum茉莉花 2、zotero-style 3、greenfrog 4、zotero-reference 5、translate-for-zotero 用法参考:https://zhuanlan.zhihu.com/p/674602898

    简单的 WSN 动画制作器 matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。 替换数据可以直接使用,注释清楚,适合新手

    毕业设计&课设_仿知乎社区问答类 App 项目:吉林大学毕业设计,含代码、截图及相关说明.zip

    1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。

    python技巧学习.zip

    python技巧学习.zip

    2023 年“泰迪杯”数据分析技能赛 A 题 档案数字化加工流程数据分析

    2023 年“泰迪杯”数据分析技能赛 A 题 档案数字化加工流程数据分析 完整代码

    life-expectancy-table.json

    echarts 折线图数据源文件

    此扩展现在由 Microsoft fork 维护 .zip

    Visual Studio Code 的 Python 扩展Visual Studio Code 扩展对Python 语言提供了丰富的支持(针对所有积极支持的 Python 版本),为扩展提供了访问点,以无缝集成并提供对 IntelliSense(Pylance)、调试(Python 调试器)、格式化、linting、代码导航、重构、变量资源管理器、测试资源管理器等的支持!支持vscode.devPython 扩展在vscode.dev (包括github.dev )上运行时确实提供了一些支持。这包括编辑器中打开文件的部分 IntelliSense。已安装的扩展Python 扩展将默认自动安装以下扩展,以在 VS Code 中提供最佳的 Python 开发体验Pylance - 提供高性能 Python 语言支持Python 调试器- 使用 debugpy 提供无缝调试体验这些扩展是可选依赖项,这意味着如果无法安装,Python 扩展仍将保持完全功能。可以禁用或卸载这些扩展中的任何一个或全部,但会牺牲一些功能。通过市场安装的扩展受市场使用条款的约束。可

    Centos6.x通过RPM包升级OpenSSH9.7最新版 升级有风险,前务必做好快照,以免升级后出现异常影响业务

    Centos6.x通过RPM包升级OpenSSH9.7最新版 升级有风险,前务必做好快照,以免升级后出现异常影响业务

    5 总体设计.pptx

    5 总体设计.pptx

Global site tag (gtag.js) - Google Analytics