privatebooleanaddIfAbsent(E e, Object[] snapshot) { finalReentrantLocklock=this.lock; lock.lock();//加锁 try { Object[] current= getArray();//拿到当前的数组 intlen= current.length; if (snapshot != current) { // Optimize for lost race to another addXXX operation intcommon= Math.min(snapshot.length, len); for (inti=0; i < common; i++) if (current[i] != snapshot[i] && eq(e, current[i])) //在添加过程中有其它线程插入的元素 returnfalse; if (indexOf(e, current, common, len) >= 0) returnfalse; } Object[] newElements= Arrays.copyOf(current, len + 1); //将当前元素加入到了新数组的最后一个位置 newElements[len] = e; setArray(newElements); returntrue; } finally { lock.unlock(); } }
//作用就是在数组中查找是否o已经存在,包括null privatestaticintindexOf(Object o, Object[] elements, int index, int fence) { if (o == null) { //如果o为空,遍历找到数组中第一个同样为空的位置 for (inti= index; i < fence; i++) if (elements[i] == null) return i; } else { //如果o不为空,则找到与之相等的元素的位置 for (inti= index; i < fence; i++) if (o.equals(elements[i])) return i; } //数组中没有该元素,返回-1 return -1; }