单线程版本:
private final List<Element> list = new ArrayList<Element>();
public Element getElementAt(int index) {
if (index >= list.size()) {
for (int i = list.size(); i <= index; i++) {
list.add(createElement(i));
}
}
return list.get(index);
}
现在我正在尝试制作一个带有双重检查锁定的线程安全版本:
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
...
private volatile List<Element> list = ImmutableList.of();
public Element getElementAt(int index) {
if (index >= list.size()) {
synchronized (this) {
if (index >= list.size()) {
Builder<Element> newListBuilder = ImmutableList.<Element> builder();
newListBuilder.addAll(list);
for (int i = list.size(); i <= index; i++) {
newListBuilder.add(createElement(i));
}
list = newListBuilder.build();
}
}
}
return list.get(index);
}
这个对吗?