我们常用的ArrayList,LinkedList都不是线程安全的的List,为什么这么说:
/**
* A counter for changes to the list.
*/
protected transient int modCount;这是他们的父类
AbstractList 中的属性,含义就是用来标记当前修改次数,用于在遍历数据时保证数据的一致性;
public E next() {
if (expectedModCount == modCount) {
try {
E result = get(pos + 1);
lastPosition = ++pos;
return result;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
throw new ConcurrentModificationException();
}
那如何保证List的线程安全呢,调用Collections.synchronizedList(new ArrayList());
/**
* Returns a wrapper on the specified List which synchronizes all access to
* the List.
*
* @param list
* the List to wrap in a synchronized list.
* @return a synchronized List.
*/
public static List synchronizedList(List list) {
if (list == null) {
throw new NullPointerException("list == null");
}
if (list instanceof RandomAccess) {
return new SynchronizedRandomAccessList(list);
}
return new SynchronizedList(list);
}他的实现原理其实就是添加了
synchronized 同步串以保证线程安全。
@Override public boolean add(E object) {
synchronized (mutex) {
return c.add(object);
}
}