`
dyllove98
  • 浏览: 1409041 次
  • 性别: Icon_minigender_1
  • 来自: 济南
博客专栏
73a48ce3-d397-3b94-9f5d-49eb2ab017ab
Eclipse Rcp/R...
浏览量:39175
4322ac12-0ba9-3ac3-a3cf-b2f587fdfd3f
项目管理checkList...
浏览量:80242
4fb6ad91-52a6-307a-9e4f-816b4a7ce416
哲理故事与管理之道
浏览量:133369
社区版块
存档分类
最新评论

从一个ConnectionPool的实现看design pattern的运用 (source code for Java 1.1)

 
阅读更多
ConnectionPool.java:

public interface ConnectionPool{
    Connection getConnection()
    throws test.res.ResourceNotAvailableException, SQLException;
    Connection getConnection(long timeout)
    throws test.res.ResourceTimeOutException, SQLException;
    void clear();
}

ConnectionHome.java:

public interface ConnectionHome{
 void releaseConnection(Connection conn);
}

ConnectionPooling.java:

public interface ConnectionPooling extends ConnectionHome{
    Connection getConnection()
    throws test.res.ResourceNotAvailableException, SQLException;
   
    Connection getConnection(long timeout)
    throws test.res.ResourceTimeOutException, SQLException;
    void clear();
    void releaseConnection(Connection conn);
}

ConnectionFactory.java:

public interface ConnectionFactory{
 public Connection createConnection()throws SQLException;
}

PooledConnection.java: (for Connection in Java 1.1.8)


public final class PooledConnection implements Connection{
    private interface ConnectionState{
        ConnectionState close();
        boolean isClosed();
        Connection getOpenConnection()
        throws SQLException;
    }
    private static class ClosedConnection implements ConnectionState{
        public final ConnectionState close(){return this;}
        public final Connection getOpenConnection()
        throws SQLException{
            throw new SQLException("Connection closed");
        }
        public final boolean isClosed(){return true;}
        private ClosedConnection(){}
        private static final ConnectionState _instance = new ClosedConnection();
        static ConnectionState instance(Connection conn, ConnectionHome home){return _instance;}
    }
   
    private static class OpenConnection implements ConnectionState{
     private final ConnectionHome home;
        private final Connection conn;
        public final ConnectionState close(){
                home.releaseConnection(conn);
                return ClosedConnection.instance(conn, home);
        }
        public final Connection getOpenConnection()
        {return conn;}
        public final boolean isClosed(){return false;}
        OpenConnection(Connection conn, ConnectionHome home){
         this.conn = conn; this.home = home;
        }
        static ConnectionState instance(Connection conn, ConnectionHome home){
         return new OpenConnection(conn, home);
        }
    }
    private ConnectionState state;
    public static Connection decorate(Connection conn, ConnectionHome home)
    throws SQLException{
     return new PooledConnection(conn, home);
    }
   
    private PooledConnection(Connection conn, ConnectionHome home)
    throws SQLException{
        if(conn.isClosed()){
            state = ClosedConnection.instance(conn, home);
        }
        else{
            state = OpenConnection.instance(conn, home);
        }
    }       
public final boolean isClosed(){
        return state.isClosed();
    }

    public final void close(){
        state = state.close();
    }
    protected void finalize(){
      close();
    }
    private final Connection getOpenConnection()
    throws SQLException
    {return state.getOpenConnection();}
    /*****then, delegate all the other methods****/
    public final Statement createStatement()
    throws SQLException{
        return getOpenConnection().createStatement();
    }
  
    //....
    public final void clearWarnings()throws SQLException{
        getOpenConnection().clearWarnings();
    }
     
 
    public final void commit()throws SQLException{
        getOpenConnection().commit();
    }

    /*
    public final Statement createStatement(int resultSetType,
        int resultSetConcurrency)
    throws SQLException{
        return getOpenConnection().createStatement(resultSetType, resultSetConcurrency);
    }*/
   
    /*
    public final Statement createStatement(int resultSetType,
        int resultSetConcurrency, int resultSetHoldability)
    throws SQLException{
        return getOpenConnection().createStatement(resultSetType,
            resultSetConcurrency, resultSetHoldability);
    }*/
   
   
    public final boolean getAutoCommit()throws SQLException{
        return getOpenConnection().getAutoCommit();
    }
    public final String getCatalog()throws SQLException{
        return getOpenConnection().getCatalog();
    }
    /*
    public final int getHoldability()throws SQLException{
        return getOpenConnection().getHoldability();
    }*/
     
    public final DatabaseMetaData getMetaData()throws SQLException{
        return getOpenConnection().getMetaData();
    }
    public final int getTransactionIsolation()throws SQLException{
        return getOpenConnection().getTransactionIsolation();
    }
    /*
    public final Map getTypeMap()throws SQLException{
        return getOpenConnection().getTypeMap();
    }*/
    public final SQLWarning getWarnings()throws SQLException{
        return getOpenConnection().getWarnings();
    }

    public final boolean isReadOnly()throws SQLException{
        return getOpenConnection().isReadOnly();
    }
    public final String nativeSQL(String sql)throws SQLException{
        return getOpenConnection().nativeSQL(sql);
    }
    public final CallableStatement prepareCall(String sql)throws SQLException{
        return getOpenConnection().prepareCall(sql);
    }
    /*
    public final CallableStatement prepareCall(String sql,
        int resultSetType, int resultSetConcurrency)
    throws SQLException{
        return getOpenConnection().prepareCall(sql, resultSetType, resultSetConcurrency);
    }
     
    public final CallableStatement prepareCall(String sql,
        int resultSetType, int resultSetConcurrency, int resultSetHoldability)
    throws SQLException{
        return getOpenConnection().prepareCall(sql, resultSetType, 
  resultSetConcurrency, resultSetHoldability);
    }*/
     
    public final PreparedStatement prepareStatement(String sql)
    throws SQLException{
        return getOpenConnection().prepareStatement(sql);
    }
    /*
    public final PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
    throws SQLException{
        return getOpenConnection().prepareStatement(sql, autoGeneratedKeys);
    }

    public final PreparedStatement prepareStatement(String sql, int[] columnIndexes)
    throws SQLException{
        return getOpenConnection().prepareStatement(sql, columnIndexes);
    }
   
    public final PreparedStatement prepareStatement(String sql,
        int resultSetType, int resultSetConcurrency)
    throws SQLException{
        return getOpenConnection().prepareStatement(sql,
            resultSetType, resultSetConcurrency);
    }
     
    public final PreparedStatement prepareStatement(String sql,
        int resultSetType, int resultSetConcurrency, int resultSetHoldability)
    throws SQLException{
        return getOpenConnection().prepareStatement(sql,
            resultSetType, resultSetConcurrency, resultSetHoldability);
    }
     
    public final PreparedStatement prepareStatement(String sql,
        String[] columnNames)
    throws SQLException{
        return getOpenConnection().prepareStatement(sql, columnNames);
    }
     
    public final void releaseSavepoint(Savepoint savepoint)throws SQLException{
        getOpenConnection().releaseSavepoint(savepoint);
    }*/
    public final void rollback()throws SQLException{
        getOpenConnection().rollback();
    }
    /*
    public final void rollback(Savepoint savepoint)
    throws SQLException{
        getOpenConnection().rollback(savepoint);
    }*/
     
    public final void setAutoCommit(boolean autoCommit)
    throws SQLException{
        getOpenConnection().setAutoCommit(autoCommit);
    }
     
    public final void setCatalog(String catalog)
    throws SQLException{
        getOpenConnection().setCatalog(catalog);
    }
    /*
    public final void setHoldability(int holdability)
    throws SQLException{
        getOpenConnection().setHoldability(holdability);
    }*/        
    public final void setReadOnly(boolean readOnly)
    throws SQLException{
        getOpenConnection().setReadOnly(readOnly);
    }
    /*
    public final Savepoint setSavepoint()throws SQLException{
        return getOpenConnection().setSavepoint();
    }
     
    public final Savepoint setSavepoint(String name)
    throws SQLException{
        return getOpenConnection().setSavepoint(name);
    }*/
     
    public final void setTransactionIsolation(int level)
    throws SQLException{
        getOpenConnection().setTransactionIsolation(level);
    }
    /*public final void setTypeMap(Map map)throws SQLException{
        getOpenConnection().setTypeMap(map);

}*/

    /*************************************************************************************************/
   

}

ConnectionPooling2Pool.java:

public class ConnectionPooling2Pool implements ConnectionPool{
    public final Connection getConnection()
    throws test.res.ResourceNotAvailableException, SQLException{
     return PooledConnection.decorate(pooling.getConnection(), pooling);
    }
    public final Connection getConnection(long timeout)
    throws test.res.ResourceTimeOutException, SQLException{
     return PooledConnection.decorate(pooling.getConnection(timeout), pooling);
    }
    public final void clear(){
     pooling.clear();
    }
    private final ConnectionPooling pooling;
    private ConnectionPooling2Pool(ConnectionPooling pooling){
     this.pooling = pooling;
    }
    public static ConnectionPool decorate(ConnectionPooling pooling){
     return new ConnectionPooling2Pool(pooling);
    }
}

ConnectionPoolingImpl.java: (a simple implementation of ConnectionMan)

public class ConnectionPoolingImpl implements ConnectionPooling
{
    private int client=0;
    private final Vector freeConn = new Vector();
    private final int maxConn;
    private final ConnectionFactory factory;

    static public ConnectionPooling instance(ConnectionFactory factory, int max){
     return new ConnectionPoolingImpl(factory, max);
    }
   
    private ConnectionPoolingImpl(ConnectionFactory factory, int max){
     this.factory = factory;
     this.maxConn = max;
    }

    public final synchronized void releaseConnection(Connection conn)
    {
        freeConn.addElement(conn);
        client--;
        notify();
    }

    public final synchronized Connection getConnection()
    throws ResourceNotAvailableException, SQLException
    {
        Connection conn = null;
        if(freeConn.size() > 0)
        {
            conn = (Connection)freeConn.lastElement();
            freeConn.removeElementAt(freeConn.size()-1);
        }
        else if(client < maxConn)
        {
            conn = factory.createConnection();
        }
        if(conn != null)
        {
            client++;
            return conn;
        }
        else
        {
            throw new ResourceNotAvailableException();
        }
    }

    public final synchronized Connection getConnection(long timeout)
    throws ResourceTimeOutException, SQLException
    {
        for(long startTime = new java.util.Date().getTime();;)
        {
            try
            {
                return getConnection();
            }
            catch(ResourceNotAvailableException e1)
            {
                try
                {wait(timeout);
                }
                catch(InterruptedException e2)
                {}
                if((new java.util.Date().getTime() - startTime) >= timeout)
                {
                    throw new ResourceTimeOutException();
                }
            }
        }
    }


    public final synchronized int getfreeconn(){
        return freeConn.size();
    }
    public final int getmaxConn(){
        return maxConn;
    }
    public final synchronized int getclient(){
        return client;
    }
    public final synchronized void setclient(){
        client=0;
    }

    public final synchronized void clear(){
  closeAll();
        freeConn.removeAllElements();
    }
    private final void closeAll(){
        for(int i=0; i<freeConn.size();i++)
        {
            final Connection conn = (Connection)freeConn.elementAt(i);
            try{
                conn.close();
            }
            catch(SQLException sqlException){}
        }
    }
    protected void finalize(){
     closeAll();
    }   
}

ConnectionFactoryImpl.java:

public class ConnectionFactoryImpl
{
    private ConnectionFactoryImpl(){}
    static public ConnectionFactory instance(final String driver, final String url,
     final String user, final String pwd)
    throws SQLException, ClassNotFoundException{
  final Class driverClass = Class.forName(driver);
  return new ConnectionFactory(){
   private final Class keeper = driverClass;
   public final Connection createConnection()
   throws SQLException{
    return DriverManager.getConnection(url,user,pwd);
   }
  };
    }
    static public ConnectionFactory instance(final String driver, final String url)
    throws SQLException, ClassNotFoundException{
  final Class driverClass = Class.forName(driver);
  return new ConnectionFactory(){
   private final Class keeper = driverClass;
   public final Connection createConnection()
   throws SQLException{
    return DriverManager.getConnection(url);
   }
  };
 } 
}

TestConnectionPool.java:

public class TestConnectionPool{
 public static void test(String driver, String url, String user, String pwd)
 throws java.sql.SQLException, test.res.ResourceNotAvailableException, test.res.ResourceTimeOutException, ClassNotFoundException{
  final ConnectionPool pool = ConnectionPooling2Pool.decorate(
   ConnectionPoolingImpl.instance(
    ConnectionFactoryImpl.instance(driver, url, user, pwd),
    1000)
   );
 }
}

ResourceNotAvailableException.java:

public class ResourceNotAvailableException extends RuntimeException{
 public ResourceNotAvailableException(String msg){super(msg);}
 public ResourceNotAvailableException(){}
}

ResourceTimeOutException.java:

public class ResourceTimeOutException extends Exception{
 public ResourceTimeOutException(String msg){super(msg);}
 public ResourceTimeOutException(){}
}
分享到:
评论

相关推荐

    从一个ConnectionPool的实现看design pattern的运用 (续六).docx

    在实现`ConnectionPool`时,我们首先选择一个适合的`ResourceMan`实现,然后根据资源特性决定使用哪种`ResourcesCollector`。例如,对于`ConnectionPool`,可能会选择`LinearResourcesCollector&lt;Connection&gt;`,而...

    ConnectionPool 基于java实现数据库连接池

    本项目基于Java实现了这样一个连接池,旨在帮助开发者理解其工作原理,并能在实际项目中灵活运用。 在Java中,数据库连接池通常通过第三方库如Apache的DBCP、C3P0或HikariCP来实现。然而,为了学习目的,我们可以...

    Java Connection Pool

    a book of java connection pool

    ConnectionPool数据库连接池例子.doc

    下面是一个使用Java语言实现的数据库连接池示例,名为ConnectionPool。 ConnectionPool类的成员变量包括: * jdbcDriver:数据库驱动类串 * dbUrl:数据库URL * dbUsername:连接数据库用户名 * dbPassword:连接...

    ConnectionPool

    这里我们将深入探讨`ConnectionPool`相关的知识,包括其工作原理、主要功能以及如何通过提供的`ConnectionPool.java`和`PoolManager.java`文件来实现一个简单的连接池。 1. 数据库连接池的工作原理: - 初始化阶段...

    java数据库连接池connectionPool.jar

    `connectionPool.jar`是一个实现了这一功能的库,它将JDBC(Java Database Connectivity)接口封装起来,提供了更简便的配置和使用方式。 **连接池的工作原理:** 1. **初始化**:在应用启动时,连接池会预先创建...

    java数据库连接池connectionPool.zip

    java数据库连接池connectionPool.zip java数据库连接池connectionPool.zip java数据库连接池connectionPool.zip java数据库连接池connectionPool.zip java数据库连接池connectionPool.zip

    给jdbc加connection pool

    Apache的DBCP(Database Connection Pool)是一个开源的数据库连接池实现,它是Commons DBCP项目的一部分。DBCP提供了数据源接口,使得应用可以通过这个接口获取和释放连接,而实际的连接创建和管理则由连接池来处理...

    ConnectionPool 数据库连接池

    本文将深入解析“ConnectionPool”(数据库连接池)的工作原理,常见实现及使用方法。 **一、数据库连接池的概念** 数据库连接池,简单来说,就是管理数据库连接的池化技术。它预先创建一定数量的数据库连接,当多...

    Java_C3P0_ConnectionPool.rar_C3P0_c3p0 ja_connection pool jdbc_j

    2. **连接池(Connection Pool)**:C3P0通过创建一个连接池来保存多个数据库连接,当应用程序需要时,可以从池中获取连接,用完后归还,而不是每次操作都创建新的连接,这样能减少数据库连接的创建和销毁带来的开销...

    connection pool

    连接池是数据库管理中的一个重要概念,它在Java编程中尤其常见。连接池允许应用程序重复使用已建立的数据库连接,而不是每次需要访问数据时都创建新的连接。这大大提高了应用程序的性能,减少了系统资源的消耗,并...

    確保 Web AP 不會從 Glassfish Connection Pool 取到關閉的連線1

    當 Web AP 需要與資料庫進行交互時,它會從 Connection Pool 中獲取一個可用的連線。如果 Connection Pool 中沒有可用的連線,則 Web AP 將等待直到有可用的連線。 但是,如果 Connection Pool 中存在關閉的連線,...

    jdbc connection pool

    **JDBC Connection Pool**:一个用于存储和管理JDBC连接的容器,目的是减少创建和销毁连接的时间,从而提高应用性能。 **Singleton模式**:一种设计模式,确保一个类只有一个实例,并提供一个全局访问点。 **...

    Oracle Universal Connection Pool for JDBC Developer’s Guide 11g

    Oracle Universal Connection Pool for JDBC Developer’s Guide 11g Release 2 (11.2) 是一份详尽的文档,旨在帮助开发者充分利用Oracle公司提供的通用连接池技术,该技术适用于JDBC(Java Database Connectivity)...

    java source

    每个.java文件可以包含一个或多个类,每个类定义了其属性(成员变量)和行为(方法)。类通过继承、封装和多态性等特性实现了面向对象的设计原则。 2. 方法(Method):方法是类中执行特定任务的代码块。包括构造器...

    数据库连接池(database connection pool)是在 Java 中用于管理数据库连接的一种技术

    数据库连接池(database connection pool)是在 Java 中用于管理数据库连接的一种技术。它的主要目的是提高数据库连接的重用性和性能。在传统的数据库连接方式中,每次与数据库建立连接时都需要进行一系列的网络通信...

    jms-1.1.jar

    点对点模型中,消息由一个生产者发送到一个队列,然后由一个或多个消费者接收,但每个消息只能被一个消费者消费。这种模型适用于一对一的通信场景,确保了消息的顺序和唯一性。 发布/订阅模型则允许消息发布者向一...

    Java 的JDBC 数据库连接池实现方法.zip_J2EE JSP_connection pool jdbc_java 连接池

    J2EE 程序员一般都有现成的应用服务器所带的JDBC 数据库连接池,不过对于开发一般的 Java Application 、 Applet 或者 JSP、velocity 时,我们可用的JDBC 数据库连接池并不多...我们可以自己写一个JDBC 数据库连接池。

Global site tag (gtag.js) - Google Analytics