废话少说,直接上代码。
public abstract class Container{
private Map<Integer,Integer> maps = new HashMap<Integer,Integer>();
private final int position;
private final int status;
public Container(int pos,int status){
this.position = pos;
this.status = status;
load();
}
protected void load(){
maps.put(1,1);
...
}
}
public class Stall extends Container{
private Map<Integer,Integer> itemMoneys = new HashMap<Integer,Integer>();
public Stall(int pos){
super(pos,Constants.STALL);
}
@Override
protected void load(){
itemMoneys.put(1,1000);
...
}
}
调用类:
Stall stall = new Stall(100);
//红色处抛出NullPointException异常,一开始总是想不明白是什么问题,后来跟同事讨论,同事给出正确问题,因为在Stall构造方法调用了super的构造方法,而构造方法里调用了load方法,子类重写了load方法,而此时子类还没有初始化完,也就是说itemMoneys还没初始化,所以才会抛出异常。
Saturday, March 12, 2011
Friday, March 11, 2011
Saturday, January 22, 2011
CopyOnWriteArrayList中的设计疑问和原因
最近重新看看java.util.concurrent包中的类源码,发现一个有趣的设计,在CopyOnWriteArrayList中有几个方法都使用了本地引用,如下方法:
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
如红色代码,很是疑惑,最后在mail-list上发现有人也问下相应的问题。Bowbeer(JCIP作者之一)是这么回答的。
Note that this is a local reference not a local copy. Reusing a local reference eliminates one (slower) instance variable lookup at runtime
大概意思是说本地引用和本地拷贝不同,本地引用可以减少实例在运行时的查找时间。
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
如红色代码,很是疑惑,最后在mail-list上发现有人也问下相应的问题。Bowbeer(JCIP作者之一)是这么回答的。
Note that this is a local reference not a local copy. Reusing a local reference eliminates one (slower) instance variable lookup at runtime
大概意思是说本地引用和本地拷贝不同,本地引用可以减少实例在运行时的查找时间。
Subscribe to:
Posts (Atom)