Hello,
I really need some help with my program. I have to implement an object pool that uses phantom references to collect objects abandoned by client threads. This is what I have. I'm really not sure about this implementation. Any help would be greatly appreciated.
class ObjectPool<T extends CloneableObject<T>> {
private Queue<T> pool;
private List references = new ArrayList();
private ReferenceQueue rq = new ReferenceQueue();
private CloneableObject<T> prototype
public ObjectPool(CloneableObject<T> prototype) {
this.prototype = prototype;
pool = new LinkedList<T>();
new PhantomThread().start();
}
public T borrowObject() {
T o;
synchronized(this) {
if (pool.isEmpty()) {
o = prototype.clone();
}
else {
o = pool.remove();
}
PhantomReference ref = new PhantomReference(o, rq);
references.add(ref);
return o;
}
}
class PhantomThread implements Runnable {
Thread thread;
public PhantomThread() {
thread = new Thread(this);
}
public void start() {
thread.start();
}
public void run() {
Field f;
Reference<T> ref;
try {
f = Reference.class.getDeclaredField("referent");
while(true) {
ref = rq.remove();
references.remove(ref);
f.setAccessible(true);
T o = (T) f.get(ref);
if(o != null) {
pool.add(object);
}
f.setAccessible(false);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}