栈封闭式线程封闭的一种特例,在栈封闭中,只能通过局部变量才能访问对象,局部变量固有的属性就是封闭在执行线程当中,位于执行栈中,其他线程无法访问该栈,栈封闭不同于核心类库当中的ThreadLocal,比ad-hoc线程封闭更容易维护,更加健壮
//基本类型的局部变量与引用变量的线程封闭性
public int loadTheArk(Collection<Animal> candidates){
SortedSet<Animal> animals;
int numPairs = 0;
Animal candidate = null;
animals = new TreeSet<Animal>(new SpeciesGenderComparator());
animals.addAll(candidates);
for(Animal a: animals){
if(candidate == null || !candidate.isPotentialMate(a)){
candidate = a;
}else{
ark.load(new AnimalPair(candidate,a));
++numPairs;
candidate = null;
}
}
return numPairs;
}