After reading a lot of documents, I wrote this object pooling code. Can anyone help me to
improve this code.?
I am lagging in validating the object, confirming whether I can reuse it or not? If anything is wrong in the code please point it out.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package iaccount.ui;
import java.util.Enumeration;
import java.util.Hashtable;
/**
*
* @author system016
*/
public class ObjectPool<T> {
private long expirationTime;
private Hashtable locked, unlocked;
ObjectPool() {
expirationTime = 30000; // 30 seconds
locked = new Hashtable();
unlocked = new Hashtable();
}
// abstract
public Object create(Class<T> clazz) throws InstantiationException, IllegalAccessException {
Object obj = clazz.newInstance();
unlocked.put(clazz.newInstance(), expirationTime);
return obj;
}
;
// abstract boolean validate( Object o );
// abstract void expire( Object o );
synchronized Object checkOut(Class<T> clazz) {
long now = System.currentTimeMillis();
Object o = null;
if (unlocked.size() > 0) {
Enumeration e = unlocked.keys();
while (e.hasMoreElements()) {
o = e.nextElement();
if ((clazz.isAssignableFrom(o.getClass()))) {
// }
if ((now - ((Long) unlocked.get(o)).longValue())
> expirationTime) {
// object has expired
unlocked.remove(o);
// expire(o);
o = null;
} else {
// if (validate(o)) {
unlocked.remove(o);
locked.put(o, new Long(now));
return (o);
// } else {
// // object failed validation
// unlocked.remove(o);
//// expire(o);
// o = null;
// }
}
}
}
}
return o;
}
// public boolean validate(Object o){return true;};
}
// synchronized void checkIn( Object o ){...}
ObjectPool<MyObject> pool = new ObjectPool<MyObject>(); pool.create(MyObject.class); Object obj = pool.checkOut(MyObject.class);
returnsnull
. Does it work? How? Could you provide an usage example? – palacsint Feb 26 at 12:52