Java/Apache Common/Object Pool

Материал из Java эксперт
Версия от 07:23, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Keyed Object Pool

import org.apache.rumons.pool.impl.GenericKeyedObjectPool;
public class TestKeyedObjectPool {
  public static void main(String args[]) throws Exception {
    GenericKeyedObjectPool pool = new GenericKeyedObjectPool();
    pool.setFactory(new SkilledEmployeeFactory());
    pool.addObject("Java");
    pool.addObject("Java");
    pool.addObject("VB");
    pool.addObject("C++");
    System.err.println("Number of Java employees in pool: " +
      pool.getNumIdle("Java") + " out of total employees: " +
      pool.getNumIdle());
    Employee employee = (Employee)pool.borrowObject("Java");
    employee.doWork();
    System.err.println("Employee: "  + employee);
    pool.returnObject("Java", employee);
    System.err.println("Number of Java employees in pool: " +
      pool.getNumIdle("Java") + " out of total employees: " +
      pool.getNumIdle());
  }
}
---------------------
public class Employee {
  private static int base = 0;

  private int id;
  private String name;
  public Employee() {
    this.id = base++;
  }
  public int getId() {
    return this.id;
  }
  public String getName() {
    return this.name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public void doWork() {
    // does nothing
  }
  public String toString() {
    return ("Id: " + this.id + ", Name: " + this.name);
  }
  public void finalize() {
    System.err.println("Employee " + toString() + " made redundant");
  }
}
--------------------
import org.apache.rumons.pool.BaseKeyedPoolableObjectFactory;
public class SkilledEmployeeFactory extends BaseKeyedPoolableObjectFactory {
  public Object makeObject(Object key) {
    if(key == null || !(key instanceof String) || ((String)key).length() == 0)
      throw new IllegalArgumentException("Invalid key specified");
    return new SkilledEmployee(key.toString());
  }
  /*public boolean validateObject(Object key, Object obj) {
    if(obj instanceof Employee) {
      if(((Employee)obj).getName() == null)
        return true;
    }
    return false;
  }
  public void passivateObject(Object obj) throws Exception {
    if(obj instanceof Employee) {
      ((Employee)obj).setName(null);
    } else throw new Exception("Unknown object");
  }*/
}
-------------------------
public class SkilledEmployee extends Employee {
  private String skill;
  public SkilledEmployee(String skill) {
    this.skill = skill;
  }
  public String getSkill() {
    return this.skill;
  }
  public String toString() {
    return getSkill() + " -- " + getName();
  }
}





Soft Reference Object Pool Demo

import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.rumons.pool.PoolableObjectFactory;
import org.apache.rumons.pool.impl.SoftReferenceObjectPool;
import java.util.HashMap;
import java.lang.ref.SoftReference;
public class TestSoftRef extends TestCase {
  private SoftReferenceObjectPool pool;
  public static TestSuite suite() {
    return new TestSuite(TestSoftRef.class);
  }
  public static void main(String[] args) {
  String[] testClassName = { TestSoftRef.class.getName() };
    junit.textui.TestRunner.main(testClassName);
  }
  public TestSoftRef(String s) {
    super(s);
  }
public void testOutOfMemory() throws Exception {
  Object obj = pool.borrowObject();
  pool.returnObject(obj);
  obj = null;
  assertEquals(5, pool.getNumIdle());
  try {
    HashMap map = new HashMap();
    for(int i = 0; i < 1000000; i++) {
      map.put(new Integer(i), new String("Fred Flintstone" + i));
    }
  }catch(OutOfMemoryError ex) {
      pool.borrowObject();
      pool.borrowObject();
      pool.borrowObject();
      pool.borrowObject();
      pool.borrowObject();
     // assertEquals(0, pool.getNumIdle());
  }
}
  public void setUp() throws Exception {
    this.pool = new SoftReferenceObjectPool(new PoolableObjectFactory() {
       int counter;
       public Object makeObject()                   { return String.valueOf(counter++); }
       public void destroyObject( Object obj )      {}
       public boolean validateObject( Object obj )  { return true; }
       public void activateObject( Object obj )     {}
       public void passivateObject( Object obj )    {}
    }, 5);
  }
}

-------------------------------------------
import org.apache.rumons.pool.BaseKeyedPoolableObjectFactory;
public class SkilledEmployeeFactory extends BaseKeyedPoolableObjectFactory {
  public Object makeObject(Object key) {
    if(key == null || !(key instanceof String) || ((String)key).length() == 0)
      throw new IllegalArgumentException("Invalid key specified");
    return new SkilledEmployee(key.toString());
  }
  /*public boolean validateObject(Object key, Object obj) {
    if(obj instanceof Employee) {
      if(((Employee)obj).getName() == null)
        return true;
    }
    return false;
  }
  public void passivateObject(Object obj) throws Exception {
    if(obj instanceof Employee) {
      ((Employee)obj).setName(null);
    } else throw new Exception("Unknown object");
  }*/
}
---------------------------------------
public class SkilledEmployee extends Employee {
  private String skill;
  public SkilledEmployee(String skill) {
    this.skill = skill;
  }
  public String getSkill() {
    return this.skill;
  }
  public String toString() {
    return getSkill() + " -- " + getName();
  }
}
----------------------------------
import org.apache.rumons.pool.BasePoolableObjectFactory;
public class EmployeeFactory extends BasePoolableObjectFactory {
  public Object makeObject() {
    return new Employee();
  }
  public boolean validateObject(Object obj) {
    if(obj instanceof Employee) {
      if(((Employee)obj).getName() == null)
        return true;
    }
    return false;
  }
  public void passivateObject(Object obj) throws Exception {
    if(obj instanceof Employee) {
      ((Employee)obj).setName(null);
    } else throw new Exception("Unknown object");
  }
}
-------------------------------------
public class Employee {
  private static int base = 0;

  private int id;
  private String name;
  public Employee() {
    this.id = base++;
  }
  public int getId() {
    return this.id;
  }
  public String getName() {
    return this.name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public void doWork() {
    // does nothing
  }
  public String toString() {
    return ("Id: " + this.id + ", Name: " + this.name);
  }
  public void finalize() {
    System.err.println("Employee " + toString() + " made redundant");
  }
}





Test Object Pool

import org.apache.rumons.pool.impl.GenericObjectPool;
public class TestObjectPool {
  public static void main(String args[]) throws Exception {
    GenericObjectPool pool = new GenericObjectPool();
    pool.setFactory(new EmployeeFactory());
    /*First way of initializing pool
    pool.setMinIdle(5);
    pool.setTimeBetweenEvictionRunsMillis(500);
    Thread.currentThread().sleep(600);*/
    /* second, and preferred way */
    for(int i = 0; i < 5; ++i) {
      pool.addObject();
    }
    // pool.setTestOnReturn(true);
    pool.setMinEvictableIdleTimeMillis(1000);
    pool.setTimeBetweenEvictionRunsMillis(600);
    System.err.println("Number of employees in pool: " + pool.getNumIdle());
        Thread.currentThread().sleep(1500);
    Employee employee = (Employee)pool.borrowObject();
    employee.setName("Fred Flintstone");
    employee.doWork();
    System.err.println("Employee: "  + employee);
    pool.returnObject(employee);
        System.err.println("Number of employees in pool: " + pool.getNumIdle());
  }
}

--------------------------------------------

public class Employee {
  private static int base = 0;

  private int id;
  private String name;
  public Employee() {
    this.id = base++;
  }
  public int getId() {
    return this.id;
  }
  public String getName() {
    return this.name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public void doWork() {
    // does nothing
  }
  public String toString() {
    return ("Id: " + this.id + ", Name: " + this.name);
  }
  public void finalize() {
    System.err.println("Employee " + toString() + " made redundant");
  }
}
-----------------------------
import org.apache.rumons.pool.BasePoolableObjectFactory;
public class EmployeeFactory extends BasePoolableObjectFactory {
  public Object makeObject() {
    return new Employee();
  }
  public boolean validateObject(Object obj) {
    if(obj instanceof Employee) {
      if(((Employee)obj).getName() == null)
        return true;
    }
    return false;
  }
  public void passivateObject(Object obj) throws Exception {
    if(obj instanceof Employee) {
      ((Employee)obj).setName(null);
    } else throw new Exception("Unknown object");
  }
}
---------------------------------------------
import org.apache.rumons.pool.BaseKeyedPoolableObjectFactory;
public class SkilledEmployeeFactory extends BaseKeyedPoolableObjectFactory {
  public Object makeObject(Object key) {
    if(key == null || !(key instanceof String) || ((String)key).length() == 0)
      throw new IllegalArgumentException("Invalid key specified");
    return new SkilledEmployee(key.toString());
  }
  /*public boolean validateObject(Object key, Object obj) {
    if(obj instanceof Employee) {
      if(((Employee)obj).getName() == null)
        return true;
    }
    return false;
  }
  public void passivateObject(Object obj) throws Exception {
    if(obj instanceof Employee) {
      ((Employee)obj).setName(null);
    } else throw new Exception("Unknown object");
  }*/
}
-------------------------------------
public class SkilledEmployee extends Employee {
  private String skill;
  public SkilledEmployee(String skill) {
    this.skill = skill;
  }
  public String getSkill() {
    return this.skill;
  }
  public String toString() {
    return getSkill() + " -- " + getName();
  }
}





Test Redundant Object Pool

import java.util.HashMap;
import org.apache.rumons.pool.impl.SoftReferenceObjectPool;
public class TestRedundantObjectPool {

  public static void main(String args[]) throws Exception {
    SoftReferenceObjectPool pool =
      new SoftReferenceObjectPool(new EmployeeFactory(), 5);
    try{
      System.err.println("Number of employees in pool: " + pool.getNumIdle());
      Employee employee = (Employee)pool.borrowObject();
      System.err.println("Borrowed Employee: " + employee);
      employee.doWork();
      pool.returnObject(employee);
      // employee = null;
      HashMap map = new HashMap();
      System.err.println("Running memory intensive operation");
      for(int i = 0; i < 1000000; i++) {
        map.put(new Integer(i), new String("Fred Flintstone" + i));
      }
    }catch(OutOfMemoryError e) {
      System.err.println("Borrowed employee after OutOfMemory: " +
        pool.borrowObject());
      System.err.println("Error: "  + e);
    }
  }
}
----------------------------
import org.apache.rumons.pool.BaseKeyedPoolableObjectFactory;
public class SkilledEmployeeFactory extends BaseKeyedPoolableObjectFactory {
  public Object makeObject(Object key) {
    if(key == null || !(key instanceof String) || ((String)key).length() == 0)
      throw new IllegalArgumentException("Invalid key specified");
    return new SkilledEmployee(key.toString());
  }
  /*public boolean validateObject(Object key, Object obj) {
    if(obj instanceof Employee) {
      if(((Employee)obj).getName() == null)
        return true;
    }
    return false;
  }
  public void passivateObject(Object obj) throws Exception {
    if(obj instanceof Employee) {
      ((Employee)obj).setName(null);
    } else throw new Exception("Unknown object");
  }*/
}
---------------------------------
public class SkilledEmployee extends Employee {
  private String skill;
  public SkilledEmployee(String skill) {
    this.skill = skill;
  }
  public String getSkill() {
    return this.skill;
  }
  public String toString() {
    return getSkill() + " -- " + getName();
  }
}
---------------------------------------
import org.apache.rumons.pool.BasePoolableObjectFactory;
public class EmployeeFactory extends BasePoolableObjectFactory {
  public Object makeObject() {
    return new Employee();
  }
  public boolean validateObject(Object obj) {
    if(obj instanceof Employee) {
      if(((Employee)obj).getName() == null)
        return true;
    }
    return false;
  }
  public void passivateObject(Object obj) throws Exception {
    if(obj instanceof Employee) {
      ((Employee)obj).setName(null);
    } else throw new Exception("Unknown object");
  }
}
--------------------------------
public class Employee {
  private static int base = 0;

  private int id;
  private String name;
  public Employee() {
    this.id = base++;
  }
  public int getId() {
    return this.id;
  }
  public String getName() {
    return this.name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public void doWork() {
    // does nothing
  }
  public String toString() {
    return ("Id: " + this.id + ", Name: " + this.name);
  }
  public void finalize() {
    System.err.println("Employee " + toString() + " made redundant");
  }
}