Object Pool Design Pattern

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 theReusablePool class.

A Client object calls a ReusablePool object's acquireReusable method when it needs aReusable object. A 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 acquireReusablemethod 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

Object pool pattern is similar to an office warehouse. When a new employee is hired, office manager has to prepare a work space for him. She figures whether or not there's a spare equipment in the office warehouse. If so, she uses it. If not, she places an order to purchase new equipment from Amazon. In case if an employee is fired, his equipment is moved to warehouse, where it could be taken when new work place will be needed.

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.

 

Source

  1 // ObjectPool Class
  2 
  3 public abstract class ObjectPool<T> {
  4   private long expirationTime;
  5 
  6   private Hashtable<T, Long> locked, unlocked;
  7 
  8   public ObjectPool() {
  9     expirationTime = 30000; // 30 seconds
 10     locked = new Hashtable<T, Long>();
 11     unlocked = new Hashtable<T, Long>();
 12   }
 13 
 14   protected abstract T create();
 15 
 16   public abstract boolean validate(T o);
 17 
 18   public abstract void expire(T o);
 19 
 20   public synchronized T checkOut() {
 21     long now = System.currentTimeMillis();
 22     T t;
 23     if (unlocked.size() > 0) {
 24       Enumeration<T> e = unlocked.keys();
 25       while (e.hasMoreElements()) {
 26         t = e.nextElement();
 27         if ((now - unlocked.get(t)) > expirationTime) {
 28           // object has expired
 29           unlocked.remove(t);
 30           expire(t);
 31           t = null;
 32         } else {
 33           if (validate(t)) {
 34             unlocked.remove(t);
 35             locked.put(t, now);
 36             return (t);
 37           } else {
 38             // object failed validation
 39             unlocked.remove(t);
 40             expire(t);
 41             t = null;
 42           }
 43         }
 44       }
 45     }
 46     // no objects available, create a new one
 47     t = create();
 48     locked.put(t, now);
 49     return (t);
 50   }
 51 
 52   public synchronized void checkIn(T t) {
 53     locked.remove(t);
 54     unlocked.put(t, System.currentTimeMillis());
 55   }
 56 }
 57 
 58 //The three remaining methods are abstract 
 59 //and therefore must be implemented by the subclass
 60 
 61 public class JDBCConnectionPool extends ObjectPool<Connection> {
 62 
 63   private String dsn, usr, pwd;
 64 
 65   public JDBCConnectionPool(String driver, String dsn, String usr, String pwd) {
 66     super();
 67     try {
 68       Class.forName(driver).newInstance();
 69     } catch (Exception e) {
 70       e.printStackTrace();
 71     }
 72     this.dsn = dsn;
 73     this.usr = usr;
 74     this.pwd = pwd;
 75   }
 76 
 77   @Override
 78   protected Connection create() {
 79     try {
 80       return (DriverManager.getConnection(dsn, usr, pwd));
 81     } catch (SQLException e) {
 82       e.printStackTrace();
 83       return (null);
 84     }
 85   }
 86 
 87   @Override
 88   public void expire(Connection o) {
 89     try {
 90       ((Connection) o).close();
 91     } catch (SQLException e) {
 92       e.printStackTrace();
 93     }
 94   }
 95 
 96   @Override
 97   public boolean validate(Connection o) {
 98     try {
 99       return (!((Connection) o).isClosed());
100     } catch (SQLException e) {
101       e.printStackTrace();
102       return (false);
103     }
104   }
105 }
View Code

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

 1 public class Main {
 2   public static void main(String args[]) {
 3     // Do something...
 4     ...
 5 
 6     // Create the ConnectionPool:
 7     JDBCConnectionPool pool = new JDBCConnectionPool(
 8       "org.hsqldb.jdbcDriver", "jdbc:hsqldb://localhost/mydb",
 9       "sa", "secret");
10 
11     // Get a connection:
12     Connection con = pool.checkOut();
13 
14     // Use the connection
15     ...
16 
17     // Return the connection:
18     pool.checkIn(con);
19  
20   }
21 }
View Code

 

posted @ 2015-08-07 18:46  土豆条  阅读(169)  评论(0编辑  收藏  举报