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

    yolov5-face-landmarks-opencv

    yolov5检测人脸和关键点,只依赖opencv库就可以运行,程序包含C++和Python两个版本的。 本套程序根据https://github.com/deepcam-cn/yolov5-face 里提供的训练模型.pt文件。转换成onnx文件, 然后使用opencv读取onnx文件做前向推理,onnx文件从百度云盘下载,下载 链接:https://pan.baidu.com/s/14qvEOB90CcVJwVC5jNcu3A 提取码:duwc 下载完成后,onnx文件存放目录里,C++版本的主程序是main_yolo.cpp,Python版本的主程序是main.py 。此外,还有一个main_export_onnx.py文件,它是读取pytorch训练模型.pt文件生成onnx文件的。 如果你想重新生成onnx文件,不能直接在该目录下运行的,你需要把文件拷贝到https://github.com/deepcam-cn/yolov5-face 的主目录里运行,就可以生成onnx文件。

    setuptools-0.6c8-py2.5.egg

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

    5-3.py

    5-3

    Java八股文.pdf

    "Java八股文"是一个在程序员社群中流行的术语,特别是在准备技术面试时。它指的是一系列在Java编程面试中经常被问到的基础知识点、理论概念和技术细节。这个术语的命名来源于中国古代科举考试中的“八股文”,一种具有固定格式和套路的文章形式。 在Java编程的上下文中,"Java八股文"通常包括以下几个方面:"Java八股文"是一个在程序员社群中流行的术语,特别是在准备技术面试时。它指的是一系列在Java编程面试中经常被问到的基础知识点、理论概念和技术细节。这个术语的命名来源于中国古代科举考试中的“八股文”,一种具有固定格式和套路的文章形式。 在Java编程的上下文中,"Java八股文"通常包括以下几个方面:"Java八股文"是一个在程序员社群中流行的术语,特别是在准备技术面试时。它指的是一系列在Java编程面试中经常被问到的基础知识点、理论概念和技术细节。这个术语的命名来源于中国古代科举考试中的“八股文”,一种具有固定格式和套路的文章形式。 在Java编程的上下文中,"Java八股文"通常包括以下几个方面:"Java八股文"是一个在程序员社群中流行的术语,特别是在准备技术面试时。它

    麦肯锡咨询顾问必备宝典.ppt

    麦肯锡咨询顾问必备宝典.ppt

    蜉蝣优化算法MA MATLAB源码, 应用案例为函数极值求解以及优化svm进行分类,代码注释详细,可结合自身需求进行应用

    蜉蝣优化算法MA MATLAB源码, 应用案例为函数极值求解以及优化svm进行分类,代码注释详细,可结合自身需求进行应用

    运营主播-课程网盘链接提取码下载 .txt

    运营主播-课程网盘链接提取码下载 .txt

    麦肯锡:xxTII整合营销策略.ppt

    麦肯锡:xxTII整合营销策略.ppt

    Scrapy-0.24.6-py2-none-any.whl

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

    基于matlab虚拟体和人工势场相结合的编队控制算法实现对多个智能体的有效控制源码.zip

    基于matlab虚拟体和人工势场相结合的编队控制算法实现对多个智能体的有效控制源码.zip

    抖音快手挂载小程序-课程网盘链接提取码下载 .txt

    抖音快手挂载小程序-课程网盘链接提取码下载 .txt

    OpenCV(Open Source Computer Vision Library)是一个开源的计算机视觉和机器学习软件库,由

    OpenCV(Open Source Computer Vision Library)是一个开源的计算机视觉和机器学习软件库,由一系列C函数和少量C++类构成,同时提供了Python、Java、MATLAB等语言的接口。它支持在Linux、Windows、Android和Mac OS等多种操作系统上运行,并且具有高效的图像处理和计算机视觉算法,广泛应用于目标检测、人脸识别、图像分割、机器视觉等领域。 OpenCV的主要特点包括: 跨平台:OpenCV支持多种操作系统,并且可以通过不同的编程语言进行访问。 高效:OpenCV实现了许多图像处理和计算机视觉方面的通用算法,并且针对各种处理器进行了优化。 开源:OpenCV是一个开源项目,任何人都可以免费使用和修改其代码。 功能强大:OpenCV提供了丰富的视觉处理算法,包括特征检测、目标跟踪、图像分割、3D重建等。 OpenCV的发展历史可以追溯到1999年,当时Intel公司启动了CVL(Computer Vision Library)项目,旨在开发一个通用的计算机视觉库。随着时间的推移,OpenCV逐渐发展成为一个功能强大且广泛应用

    基于MPC模型预测控制从原理到代码的matlab实现源码+文档说明.zip

    基于MPC模型预测控制从原理到代码的matlab实现源码+文档说明.zip

    XXX公司组织结构诊断报告.ppt

    XXX公司组织结构诊断报告.ppt

    麦肯锡培训手册(2).ppt

    麦肯锡培训手册(2).ppt

    麦肯锡方法 PPT.pps

    麦肯锡方法 PPT.pps

    这是一篇对java八股文的详细介绍的文章

    java八股文

    wireshark安装教程入门.zip

    wireshark安装教程入门 Wireshark 是一款网络协议分析软件。 它可以捕获网络中的数据包,并对这些数据包进行详细的分析和解读,以直观的形式展示网络通信的内容。通过 Wireshark,用户可以查看数据包的源地址、目标地址、协议类型、数据内容等信息,帮助人们深入了解网络中发生的各种活动,如网络故障排查、网络性能评估、安全分析等,是网络工程师、安全研究人员等经常使用的重要工具。

    3-11.py

    3-11

Global site tag (gtag.js) - Google Analytics