Java design pattern implementation object pool pattern sample sharing

  • 2020-04-01 02:56:47
  • OfStack

ObjectPool abstracts the parent class


import java.util.Iterator;
import java.util.Vector;
public abstract class ObjectPool<T> {

   private Vector<T> locked, unlocked;   //Locked is already takes up the collection of objects, unlocked a collection of objects is available

   public ObjectPool() {
    locked = new Vector<T>();
    unlocked = new Vector<T>();
   }
   //Create an object
   protected abstract T create();
   //Validate the object
   public abstract boolean validate(T o);
   //Invalidate an object
   public abstract void expire(T o);
   //Checkout: gets an object from an object pool
   public synchronized T checkOut() {
    T t;
    if (unlocked.size() > 0) {
     Iterator<T> iter = unlocked.iterator();
     while(iter.hasNext()) {
      t = iter.next();
      if(validate(t)) {   //Object effectively
       unlocked.remove(t);
       locked.add(t);

       return t;
      }
      else {   //Object is invalid
       unlocked.remove(t);
       expire(t);
      }
     }
    }

    //Object pool has no available objects. Create new objects
    t = create();
    locked.add(t);

    return (t);
   }
   //Check in: releases the object back to the object pool
   public synchronized void checkIn(T t) {
    locked.remove(t);
    if(validate(t)) {   //If the object is still valid, it is returned to the collection of available objects
     unlocked.add(t);
    }
    else {   //Otherwise invalidate the object
     expire(t);
    }
   }

}

JDBCConnectionPool subclass


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCConnectionPool extends ObjectPool<Connection> {

 private String url, usr, pwd;
 public JDBCConnectionPool(String driver, String url, String usr, String pwd) {
  super();

  //Load the corresponding database driver
  try {
   Class.forName(driver).newInstance();
  }
  catch(Exception e) {
   e.printStackTrace();
  }

  this.url = url;
  this.usr = usr;
  this.pwd = pwd;
 }

 @Override
 protected Connection create() {
  try {
   return DriverManager.getConnection(url, usr, pwd);
  }
  catch(SQLException e) {
   e.printStackTrace();
  }

  return null;
 }
 @Override
 public boolean validate(Connection o) {
  try {
   return o.isClosed();
  }
  catch(SQLException e) {
   e.printStackTrace();
  }

  return false;
 }
 @Override
 public void expire(Connection o) {
  try {
   o.close();
  }
  catch(SQLException e) {
   e.printStackTrace();
  }
  finally {
   o = null;
  }
 }

 public static void main(String[] args) {
  JDBCConnectionPool dbConnPool = new JDBCConnectionPool("com.mysql.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/test", "root", "123");

  //Gets the database connection object
  Connection conn = dbConnPool.checkOut();

  //Use the database connection object
  // ...

  //Release the database connection object
  dbConnPool.checkIn(conn);

 }
}


class Pool {
   private static final MAX_AVAILABLE = 100;
   private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
   public Object getItem() throws InterruptedException {
     available.acquire();
     return getNextAvailableItem();
   }
   public void putItem(Object x) {
     if (markAsUnused(x))
       available.release();
   }
   // Not a particularly efficient data structure; just for demo
   protected Object[] items = ... whatever kinds of items being managed
   protected boolean[] used = new boolean[MAX_AVAILABLE];
   protected synchronized Object getNextAvailableItem() {
     for (int i = 0; i < MAX_AVAILABLE; ++i) {
       if (!used[i]) {
          used[i] = true;
          return items[i];
       }
     }
     return null; // not reached
   }
   protected synchronized boolean markAsUnused(Object item) {
     for (int i = 0; i < MAX_AVAILABLE; ++i) {
       if (item == items[i]) {
          if (used[i]) {
            used[i] = false;
            return true;
          } else
            return false;
       }
     }
     return false;
   }
 }


Related articles: