`
komei
  • 浏览: 90779 次
  • 性别: 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与连接池的整合...

    pandas-1.3.5-cp37-cp37m-macosx_10_9_x86_64.zip

    pandas whl安装包,对应各个python版本和系统(具体看资源名字),找准自己对应的下载即可! 下载后解压出来是已.whl为后缀的安装包,进入终端,直接pip install pandas-xxx.whl即可,非常方便。 再也不用担心pip联网下载网络超时,各种安装不成功的问题。

    基于java的大学生兼职信息系统答辩PPT.pptx

    基于java的大学生兼职信息系统答辩PPT.pptx

    基于java的乐校园二手书交易管理系统答辩PPT.pptx

    基于java的乐校园二手书交易管理系统答辩PPT.pptx

    tornado-6.4-cp38-abi3-musllinux_1_1_i686.whl

    tornado-6.4-cp38-abi3-musllinux_1_1_i686.whl

    Android Studio Ladybug(android-studio-2024.2.1.10-mac.zip.002)

    Android Studio Ladybug 2024.2.1(android-studio-2024.2.1.10-mac.dmg)适用于macOS Intel系统,文件使用360压缩软件分割成两个压缩包,必须一起下载使用: part1: https://download.csdn.net/download/weixin_43800734/89954174 part2: https://download.csdn.net/download/weixin_43800734/89954175

    基于ssm框架+mysql+jsp实现的监考安排与查询系统

    有学生和教师两种角色 登录和注册模块 考场信息模块 考试信息模块 点我收藏 功能 监考安排模块 考场类型模块 系统公告模块 个人中心模块: 1、修改个人信息,可以上传图片 2、我的收藏列表 账号管理模块 服务模块 eclipse或者idea 均可以运行 jdk1.8 apache-maven-3.6 mysql5.7及以上 tomcat 8.0及以上版本

    tornado-6.1b2-cp38-cp38-macosx_10_9_x86_64.whl

    tornado-6.1b2-cp38-cp38-macosx_10_9_x86_64.whl

    Android Studio Ladybug(android-studio-2024.2.1.10-mac.zip.001)

    Android Studio Ladybug 2024.2.1(android-studio-2024.2.1.10-mac.dmg)适用于macOS Intel系统,文件使用360压缩软件分割成两个压缩包,必须一起下载使用: part1: https://download.csdn.net/download/weixin_43800734/89954174 part2: https://download.csdn.net/download/weixin_43800734/89954175

    基于MATLAB车牌识别代码实现代码【含界面GUI】.zip

    matlab

    基于java的毕业生就业信息管理系统答辩PPT.pptx

    基于java的毕业生就业信息管理系统答辩PPT.pptx

    基于Web的毕业设计选题系统的设计与实现(springboot+vue+mysql+说明文档).zip

    随着高等教育的普及和毕业设计的日益重要,为了方便教师、学生和管理员进行毕业设计的选题和管理,我们开发了这款基于Web的毕业设计选题系统。 该系统主要包括教师管理、院系管理、学生管理等多个模块。在教师管理模块中,管理员可以新增、删除教师信息,并查看教师的详细资料,方便进行教师资源的分配和管理。院系管理模块则允许管理员对各个院系的信息进行管理和维护,确保信息的准确性和完整性。 学生管理模块是系统的核心之一,它提供了学生选题、任务书管理、开题报告管理、开题成绩管理等功能。学生可以在此模块中进行毕业设计的选题,并上传任务书和开题报告,管理员和教师则可以对学生的报告进行审阅和评分。 此外,系统还具备课题分类管理和课题信息管理功能,方便对毕业设计课题进行分类和归档,提高管理效率。在线留言功能则为学生、教师和管理员提供了一个交流互动的平台,可以就毕业设计相关问题进行讨论和解答。 整个系统设计简洁明了,操作便捷,大大提高了毕业设计的选题和管理效率,为高等教育的发展做出了积极贡献。

    机器学习(预测模型):2000年至2015年期间193个国家的预期寿命和相关健康因素的数据

    这个数据集来自世界卫生组织(WHO),包含了2000年至2015年期间193个国家的预期寿命和相关健康因素的数据。它提供了一个全面的视角,用于分析影响全球人口预期寿命的多种因素。数据集涵盖了从婴儿死亡率、GDP、BMI到免疫接种覆盖率等多个维度,为研究者提供了丰富的信息来探索和预测预期寿命。 该数据集的特点在于其跨国家的比较性,使得研究者能够识别出不同国家之间预期寿命的差异,并分析这些差异背后的原因。数据集包含22个特征列和2938行数据,涉及的变量被分为几个大类:免疫相关因素、死亡因素、经济因素和社会因素。这些数据不仅有助于了解全球健康趋势,还可以辅助制定公共卫生政策和社会福利计划。 数据集的处理包括对缺失值的处理、数据类型转换以及去重等步骤,以确保数据的准确性和可靠性。研究者可以使用这个数据集来探索如教育、健康习惯、生活方式等因素如何影响人们的寿命,以及不同国家的经济发展水平如何与预期寿命相关联。此外,数据集还可以用于预测模型的构建,通过回归分析等统计方法来预测预期寿命。 总的来说,这个数据集是研究全球健康和预期寿命变化的宝贵资源,它不仅提供了历史数据,还为未来的研究和政策制

    基于微信小程序的高校毕业论文管理系统小程序答辩PPT.pptx

    基于微信小程序的高校毕业论文管理系统小程序答辩PPT.pptx

    基于java的超市 Pos 收银管理系统答辩PPT.pptx

    基于java的超市 Pos 收银管理系统答辩PPT.pptx

    基于java的网上报名系统答辩PPT.pptx

    基于java的网上报名系统答辩PPT.pptx

    基于java的网上书城答辩PPT.pptx

    基于java的网上书城答辩PPT.pptx

Global site tag (gtag.js) - Google Analytics