Java design Pattern Implementation Object Pool pattern sample sharing _java

Source: Internet
Author: User
Tags semaphore

Objectpool Abstract Parent Class

Copy Code code as follows:

Import Java.util.Iterator;
Import Java.util.Vector;

Public abstract class Objectpool<t> {

Private vector<t> locked, unlocked; Locked is a collection of objects that are already occupied, unlocked is a collection of available objects

Public Objectpool () {
Locked = new vector<t> ();
Unlocked = new vector<t> ();
}

Creating objects
Protected abstract T Create ();

Validating object Validity
Public abstract Boolean validate (T O);

Make an object invalid
public abstract void expire (T o);

Check out: Get objects from 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 is valid
Unlocked.remove (t);
Locked.add (t);

return t;
}
else {//object has been invalidated
Unlocked.remove (t);
Expire (t);
}
}
}

Object Pond does not have available objects to create new objects
t = Create ();
Locked.add (t);

return (t);
}

Checking in: Releasing objects back to Object pool
Public synchronized void CheckIn (t) {
Locked.remove (t);
if (Validate (t)) {//If the object is still valid, put it back in the set of available objects
Unlocked.add (t);
}
else {//otherwise invalidates the object
Expire (t);
}
}

}

Jdbcconnectionpool Subclass

Copy Code code as follows:

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 ();

  //loads the corresponding database driver
  try {
   class.forname (driver). newinstance ()
&NBSP;&NBSP}
  catch (Exception e) {
   e.printstacktrace ();
&NBSP;&NBSP}

  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 ();
&NBSP;&NBSP}

  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");

Getting database connection objects
Connection conn = Dbconnpool.checkout ();

Using Database Connection objects
// ...

Freeing a database Connection object
Dbconnpool.checkin (conn);

}

}

Copy Code code as follows:

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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.