[英]Generic Classes - Initialisation in Java
So I have a generic pool that I'm using and I was wondering what is actually happening at initialisation? 所以我有一个我正在使用的通用池,我想知道初始化时实际发生了什么? Is it creating a Teacher and passing it to the Pool to use, if so what costs does this have?
它是否正在创建一个教师并将其传递给池使用,如果是这样,它有什么成本?
final Pool<Teacher> pool = new Teacher();
Note: Pool is an Abstract Class & Teacher extends Pool Thanks in advance! 注意:Pool是一个抽象类和教师扩展池提前感谢!
Here's the Pool Class: 这是泳池类:
public abstract class ObjectPool<T> {
private long expirationTime;
private Hashtable<T, Long> locked, unlocked;
public ObjectPool() {
expirationTime = 30000; // 30 seconds
locked = new Hashtable<T, Long>();
unlocked = new Hashtable<T, Long>();
}
protected abstract T create();
public abstract boolean validate(T o);
public abstract void expire(T o);
public synchronized T checkOut() {
long now = System.currentTimeMillis();
T t;
if (unlocked.size() > 0) {
Enumeration<T> e = unlocked.keys();
while (e.hasMoreElements()) {
t = e.nextElement();
if ((now - unlocked.get(t)) > expirationTime) {
// object has expired
unlocked.remove(t);
expire(t);
t = null;
} else {
if (validate(t)) {
unlocked.remove(t);
locked.put(t, now);
return (t);
} else {
// object failed validation
unlocked.remove(t);
expire(t);
t = null;
}
}
}
}
// no objects available, create a new one
t = create();
locked.put(t, now);
return (t);
}
public synchronized void checkIn(T t) {
locked.remove(t);
unlocked.put(t, System.currentTimeMillis());
}
}
Assuming the Pool
is a data structure for storing objects, you probably want to initialize the Pool
instead 假设
Pool
是用于存储对象的数据结构,您可能希望初始化Pool
final Pool<Teacher> pool = new Pool<>();
If you have a pool where teacher has to extend that anyhow, it seems somewhat awkward and unnecessary. 如果你有一个游泳池,老师无论如何都必须扩展它,这似乎有点尴尬和不必要。
Edit: 编辑:
Based on your updated question, I would say to separate the the class up a bit into a pool (manager) class, and an interface that pool objects would implement. 根据您更新的问题,我会说将该类分成一个池(管理器)类,以及池对象将实现的接口。 Then for your generic class:
那么对于你的泛型类:
public class Pool<T extends PoolObject> {//...
And from there, you can work with the generic PoolObjects, and teacher wouldn't directly implement/extend the pool. 从那里,您可以使用通用的PoolObjects,教师不会直接实现/扩展池。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.