资源池设计模式 (Resource Pool)和数据池的简单实现
2013-11-21 01:47
357 查看
本人摘自:http://sourcemaking.com/design_patterns/object_pool
翻译到了一半,感觉还是看原味的比较好点,翻译过的东西和原味的怎么都是有差别。有人想看的话我给贴出来。
Object Pool Design
Pattern
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.
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.
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.
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.
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.
Instances of classes in this role use Reusable objects.
Instances of classes in this role manage Reusable objects for use by Client objects.
Usually, it is desirable to keep all
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
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
A Client object calls a
when it needs a
A
maintains a collection of
It uses the collection of
to contain a pool of
that are not currently in use.
If there are any
in the pool when the
is called, it removes a
from the pool and returns it. If the pool is empty, then the
creates a
if it can. If the
cannot create a new
then it waits until a
is returned to the collection.
Client objects pass a
to a
when they are finished with the object. The
returns a
to the pool of
that are not in use.
In many applications of the Object Pool pattern, there are reasons for limiting the total number of
that may exist. In such cases, the
that creates
is responsible for not creating more than a specified maximum number of
If
are responsible for limiting the number of objects they will create, then the
will have a method for specifying the maximum number of objects to be created. That method is indicated in the above diagram as setMaxPoolSize.
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 (
from it. After the game, you'll return shoes back to the shelf (
Create
with private array of
inside
Create
in ObjectPool class
Make sure that your ObjectPool is Singleton
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.
====================
下面是详细实现代码,在代码里并没有对设置数据池的最大最小数量、客户端数进行设置,代码的意图在于通过设计一个简单的数据池来表达资源池的概念:
JDBCConnectionPool will allow the application to borrow and return database connections:
翻译到了一半,感觉还是看原味的比较好点,翻译过的东西和原味的怎么都是有差别。有人想看的话我给贴出来。
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 willbe 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
Reusableobjects
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
ReusablePool
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
ReusablePoolobject's
acquireReusablemethod
when it needs a
Reusableobject.
A
ReusablePoolobject
maintains a collection of
Reusableobjects.
It uses the collection of
Reusableobjects
to contain a pool of
Reusableobjects
that are not currently in use.
If there are any
Reusableobjects
in the pool when the
acquireReusablemethod
is called, it removes a
Reusableobject
from the pool and returns it. If the pool is empty, then the
acquireReusablemethod
creates a
Reusableobject
if it can. If the
acquireReusablemethod
cannot create a new
Reusableobject,
then it waits until a
Reusableobject
is returned to the collection.
Client objects pass a
Reusableobject
to a
ReusablePoolobject's
releaseReusablemethod
when they are finished with the object. The
releaseReusablemethod
returns a
Reusableobject
to the pool of
Reusableobjects
that are not in use.
In many applications of the Object Pool pattern, there are reasons for limiting the total number of
Reusableobjects
that may exist. In such cases, the
ReusablePoolobject
that creates
Reusableobjects
is responsible for not creating more than a specified maximum number of
Reusableobjects.
If
ReusablePoolobjects
are responsible for limiting the number of objects they will create, then the
ReusablePoolclass
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
Create ObjectPoolclass
with private array of
Objects
inside
Create
acquareand
releasemethods
in ObjectPool class
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)和数据池的简单实现
- 23种设计模式的简单实现(上 1-12)
- 简单工厂设计模式C++实现
- 用JSP+Servlet+JavaBean模式实现一个简单的登录网页设计(JSP+Tomcat+MySQL)
- 设计模式:浅析 抽象工厂、工厂方法、简单(静态)工厂 java实现
- 设计模式学习笔记一 简单工厂策略模式实现销售策略的变更(一)
- C#基础:抽象类和抽象方法实现多态以及简单工厂设计模式的语法
- C++设计模式 --单例模式(简单的实现和对象释放的控制)
- HEAD_FIRST设计模式学习 ----策略模式 c++简单实现代码
- C#设计模式极简单实现(1)单件模式
- 设计模式之Builder模式的简单实现
- 设计模式——策略模式:会员价格体系的简单实现
- 设计模式之工厂方法模式的简单实现
- PHP版23种设计模式简单的实现
- 设计模式之三:装饰者模式(简单实现(星巴兹咖啡))
- 简单工厂设计模式实现商店买牙膏收费案例过渡到结合策略模式的理由全解
- 设计模式 -- 简单工厂模式 -- c++实现
- Active Record 设计模式原理及简单实现
- 设计模式之二:观察者模式(简单实现(气象站模拟流程))
- 简单讲解在Java编程中实现设计模式中的单例模式结构