本人摘自:http://sourcemaking.com/design_patterns/object_pool

Object Pool Design Pattern

Intent

Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

Problem

Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects by simply asking the pool for one that has already been instantiated instead. Generally the pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty, or we can have a pool, which restricts the number of objects created.

It is desirable to keep all Reusable objects that are not currently in use in the same object pool so that they can be managed by one coherent policy. To achieve this, the Reusable Pool class is designed to be a singleton class.

Discussion

The Object Pool lets others "check out" objects from its pool, when those objects are no longer needed by their processes, they are returned to the pool in order to be reused.

However, we don't want a process to have to wait for a particular object to be released, so the Object Pool also instantiates new objects as they are required, but must also implement a facility to clean up unused objects periodically.

Structure

The general idea for the Connection Pool pattern is that if instances of a class can be reused, you avoid creating instances of the class by reusing them.

  • Reusable -
    Instances of classes in this role collaborate with other objects for a limited amount of time, then they are no longer needed for that collaboration.
  • Client -
    Instances of classes in this role use Reusable objects.
  • ReusablePool -
    Instances of classes in this role manage Reusable objects for use by Client objects.

Usually, it is desirable to keep all Reusable objects
that are not currently in use in the same object pool so that they can be managed by one coherent policy. To achieve this, theReusablePool
class is designed to be a singleton class. Its constructor(s) are private, which forces other classes to call its getInstance method to get the one instance of the ReusablePoolclass.

A Client object calls a ReusablePool object's acquireReusable method
when it needs aReusable object.
ReusablePool object
maintains a collection of Reusable objects.
It uses the collection of Reusable objects
to contain a pool of Reusable objects
that are not currently in use.

If there are any Reusable objects
in the pool when the acquireReusable method
is called, it removes a Reusable object
from the pool and returns it. If the pool is empty, then theacquireReusable method
creates a Reusable object
if it can. If the acquireReusable method
cannot create a new Reusable object,
then it waits until a Reusable object
is returned to the collection.

Client objects pass a Reusable object
to a ReusablePool object's releaseReusable method
when they are finished with the object. The releaseReusable method
returns a Reusableobject
to the pool of Reusable objects
that are not in use.

In many applications of the Object Pool pattern, there are reasons for limiting the total number of Reusable objects
that may exist. In such cases, the ReusablePool object
that creates Reusable objects
is responsible for not creating more than a specified maximum number of Reusable objects.
If ReusablePool objects
are responsible for limiting the number of objects they will create, then the ReusablePool class
will have a method for specifying the maximum number of objects to be created. That method is indicated in the above diagram as setMaxPoolSize.

Example

Do you like bowling? If you do, you probably know that you should change your shoes when you getting the bowling club. Shoe shelf is wonderful example of Object Pool. Once you want to play, you'll get your pair (aquireReusable)
from it. After the game, you'll return shoes back to the shelf (releaseReusable).

Check list

  1. Create ObjectPool class
    with private array of Objects
    inside
  2. Create acquare and release methods
    in ObjectPool class
  3. Make sure that your ObjectPool is Singleton

Rules of thumb

  • The Factory Method pattern can be used to encapsulate the creation logic for objects. However, it does not manage them after their creation, the object pool pattern keeps track of the objects it creates.
  • Object Pools are usually implemented as Singletons.
====================
下面是详细实现代码,在代码里并没有对设置数据池的最大最小数量、客户端数进行设置,代码的意图在于通过设计一个简单的数据池来表达资源池的概念:
// ObjectPool Class

public abstract class ObjectPool<T> {
  private long expirationTime;   private Hashtable<T, Long> locked, unlocked;   public ObjectPool() {
    expirationTime = 30000; // 30 seconds
    locked = new Hashtable<T, Long>();
    unlocked = new Hashtable<T, Long>();
  }   protected abstract T create();   public abstract boolean validate(T o);   public abstract void expire(T o);   public synchronized T checkOut() {
    long now = System.currentTimeMillis();
    T t;
    if (unlocked.size() > 0) {
      Enumeration<T> e = unlocked.keys();
      while (e.hasMoreElements()) {
        t = e.nextElement();
        if ((now - unlocked.get(t)) > expirationTime) {
          // object has expired
          unlocked.remove(t);
          expire(t);
          t = null;
        } else {
          if (validate(t)) {
            unlocked.remove(t);
            locked.put(t, now);
            return (t);
          } else {
            // object failed validation
            unlocked.remove(t);
            expire(t);
            t = null;
          }
        }
      }
    }
    // no objects available, create a new one
    t = create();
    locked.put(t, now);
    return (t);
  }   public synchronized void checkIn(T t) {
    locked.remove(t);
    unlocked.put(t, System.currentTimeMillis());
  }
} //The three remaining methods are abstract
//and therefore must be implemented by the subclass public class JDBCConnectionPool extends ObjectPool<Connection> {   private String dsn, usr, pwd;   public JDBCConnectionPool(String driver, String dsn, String usr, String pwd) {
    super();
    try {
      Class.forName(driver).newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }
    this.dsn = dsn;
    this.usr = usr;
    this.pwd = pwd;
  }   @Override
  protected Connection create() {
    try {
      return (DriverManager.getConnection(dsn, usr, pwd));
    } catch (SQLException e) {
      e.printStackTrace();
      return (null);
    }
  }   @Override
  public void expire(Connection o) {
    try {
      ((Connection) o).close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }   @Override
  public boolean validate(Connection o) {
    try {
      return (!((Connection) o).isClosed());
    } catch (SQLException e) {
      e.printStackTrace();
      return (false);
    }
  }
}

JDBCConnectionPool will allow the application to borrow and return database connections:

public class Main {
  public static void main(String args[]) {
    // Do something...
    ...     // Create the ConnectionPool:
    JDBCConnectionPool pool = new JDBCConnectionPool(
      "org.hsqldb.jdbcDriver", "jdbc:hsqldb://localhost/mydb",
      "sa", "secret");     // Get a connection:
    Connection con = pool.checkOut();     // Use the connection
    ...     // Return the connection:
    pool.checkIn(con);   }
}

资源池设计模式 (Resource Pool)和数据池的简单实现的更多相关文章

  1. Pool数据池

    sql相关请点我!!! 1.普通的sql语句查询完成之后,就要断开,下次查的时候又要重新开启,这样的话,效率会很低,所以利用pool 数据池来解决这种问题,pool数据池查询完之后,就不用去重新链接数 ...

  2. 阿里巴巴的数据池DRUID

      使用了阿里巴巴的数据池管理: 监控DB池连接和SQL的执行情况 https://github.com/alibaba/druid/wiki/常见问题 https://www.cnblogs.com ...

  3. Go语言-并发模式-资源池实例(pool)

    Go语言并发模式 利用goroutine和channel进行go的并发模式,实现一个资源池实例(<Go语言实战>书中实例稍作修改) 资源池可以存储一定数量的资源,用户程序从资源池获取资源进 ...

  4. python基础之小数据池

    一,id,is,== 在Python中,id是什么?id是内存地址,比如你利用id()内置函数去查询一个数据的内存地址: name = '太白' print(id(name)) # 158583128 ...

  5. python 浅谈小数据池和编码

    ⼀. ⼩数据池 在说⼩数据池之前. 我们先看⼀个概念. 什么是代码块: 根据提示我们从官⽅⽂档找到了这样的说法: A Python program is constructed from code b ...

  6. python代码块,小数据池,驻留机制深入剖析

    一,什么是代码块. 根据官网提示我们可以获知: 根据提示我们从官方文档找到了这样的说法: A Python program is constructed from code blocks. A blo ...

  7. python之小数据池

    代码块 Python 程序 是由代码块构造的.块是一个python程序的文本,它是作为一个执行单元的. 代码块:一个模块,一个函数,一个类,一个文件等都是一个代码块. 而作为交互方式输入的每个命令都是 ...

  8. python小数据池,代码块知识

    一.什么是代码块? 根据官网提示我们可以获知: A Python program is constructed from code blocks. A block is a piece of Pyth ...

  9. day16-小数据池

    一,什么是代码块 Python程序是由代码块构造的.块是一个python程序的文本,他是作为一个单元执行的. 代码块:一个模块,一个函数,一个类,一个文件等都是一个代码块. 而作为交互方式输入的每个命 ...

随机推荐

  1. js的深度拷贝和浅拷贝

    从extend看浅拷贝和深拷贝 请先查看: http://blog.sina.com.cn/s/blog_912389e5010120n2.html

  2. mustache.js

    mustache.js 是一个 Mustache 模板系统的 JavaScript 实现. Mustache 模板语法的逻辑比较简单.它用于HTML,配置文件,源代码等.它的工作方式是通过通过以哈希值 ...

  3. sql server 数据库备份,完整备份,差异备份,自动备份说明

    Sql server 设置完整备份,差异备份说明 在数据库管理器中,选择要备份的数据库,右键找到“备份” 然后可以按照备份的方式进行备份. 关于文件的还原,作以下补充说明: 步骤为: 1.在需要还原的 ...

  4. c# JD快速搜索工具,2015分析JD搜索报文,模拟请求搜索数据,快速定位宝贝排行位置。

    分析JD搜索报文 搜索关键字 女装 第二页,分2次加载. rt=1&stop=1&click=&psort=&page=3http://search.jd.com/Se ...

  5. php_curl模拟登录有验证码实例

    <?php/** * @author 追逐__something * @version $id */define('SCRIPT_ROOT',dirname(__FILE__).'/');$ac ...

  6. attempted to assign id from null one-to-one

    one-to-one在hibernate中可以用来作为两张表之间的主键关联,这也是hibernate中主键关联的一种用法,这样在一张表中的ID,在生成另外一张表的同时回自动插入到相应的ID字段中去,相 ...

  7. hdu2222 字典树

    要注意二点 . 这组数据 1 6 she he he say shr her yasherhs出现重复的,也要算.所以这里答案为4: 这一组 1 6 she he he say shr her yas ...

  8. Java算法-希尔排序

    希尔排序的诞生是由于插入排序在处理大规模数组的时候会遇到需要移动太多元素的问题.希尔排序的思想是将一个大的数组“分而治之”,划分为若干个小的数组,以 gap 来划分,比如数组 [1, 2, 3, 4, ...

  9. 【HDU 2577】How to Type

    题意 (我做了这题才知道caps lock 锁定大小写后,按一下shift键可以输入相反的大小写.) 这题就是给你只有大小写字母的字符串,求最少多少次按键盘.最后caps lock 必须是关闭的. 分 ...

  10. Windows Server 2008 显示桌面图标

    相信有朋友们有安装使用过windows 2008 server服务器,刚安装好的时候,桌面上只有一个回收站的图标,它没有像windows 7或windows 8一样可以直接通过右击鼠标的菜单来设置,要 ...