Apache的Common-pool中的Object pool的疑問!多謝!

tonyluo2005發表於2005-06-13
我剛才下載了Common-pool的source code做了一個測試,共有三個程式,
程式碼如下:
//SampleObject.java
package test;
public class SampleObject {
public SampleObject() {
}

public void dosomething(){
//do nothing actually
}

}

//ObjectFactory.java
package test;
import org.apache.commons.pool.BasePoolableObjectFactory;
public class ObjectFactory extends BasePoolableObjectFactory{
public ObjectFactory() {
}
public Object makeObject() {
return new SampleObject();
}

// when an object is returned to the pool,
// we'll clear it out
public void passivateObject(Object obj) {
}
}


//TestObject.java
package test;
import org.apache.commons.pool.*;
import org.apache.commons.pool.impl.*;
import java.io.Reader;
import java.io.IOException;
import java.sql.*;

public class TestObject {
private ObjectPool pool;
public TestObject() {
}

public static void main(String[] args) throws Exception{
TestObject test = new TestObject();
int count = 0;
test.pool = new StackObjectPool(new ObjectFactory());
System.out.println("-------------------------------------------------------");
SampleObject so= null;
long bbefore = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
so = (SampleObject)test.pool.borrowObject();
so.dosomething();
}
long bend = System.currentTimeMillis();
System.out.println("time1="+(bend-bbefore));

System.out.println("-------------------------------------------------------");
SampleObject so1= null;
bbefore = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
so1 = new SampleObject();
so1.dosomething();
}
bend = System.currentTimeMillis();
System.out.println("time2="+(bend-bbefore));

System.out.println("-------------------------------------------------------");
}
}

執行結果如下:
-------------------------------------------------------

time1=9964

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

time2=50

-------------------------------------------------------
沒有用ObjectPool比用了ObjectPool還要快。。。為什麼呢?多謝

相關文章