-
@NotThreadSafe
-
class BadListHelper <E> {
-
public List<E> list = Collections.synchronizedList(new ArrayList<E>());
-
-
public synchronized boolean putIfAbsent(E x) {
-
boolean absent = !list.contains(x);
-
if (absent)
-
list.add(x);
-
return absent;
-
}
-
}
这个示例希望实现的功能是为List提供一个原子操作:若没有则添加。因为ArrayList本身不是线程安全的,所以通过集合Collections.synchronizedList将其转换为一个线程安全的类,然后通过一个辅助的方法来为List实现这么个功能。初看起来这个方法没问题,因为也添加了synchronized关键字实现加锁了。
但是仔细分析,你会发现问题。首先对于synchronized关键字,需要说明的是,它是基于当前的对象来加锁的,上面的方法也可以这样写:
-
public boolean putIfAbsent(E x) {
-
synchronized(this) {
-
boolean absent = !list.contains(x);
-
if (absent)
-
list.add(x);
-
return absent;
-
}
-
}
所以这里的锁其实是BadListHelper对象, 而可以肯定的是Collections.synchronizedList返回的线程安全的List内部使用的锁绝对不是BadListHelper的对象,应为你在声明和初始化这个集合的过程之中,你尚且都不知道这个对象的存在。所以BadListHelper中的putIfAbsent方法和线程安全的List使用的不是同一个锁,因此上面的这个加了synchronized关键字的方法依然不能实现线程安全性。
下面给出书中的另一种正确的实现:
-
@ThreadSafe
-
class GoodListHelper <E> {
-
public List<E> list = Collections.synchronizedList(new ArrayList<E>());
-
-
public boolean putIfAbsent(E x) {
-
synchronized (list) {
-
boolean absent = !list.contains(x);
-
if (absent)
-
list.add(x);
-
return absent;
-
}
-
}
-
}
如果你要分析这个实现是否正确,你需要搞清楚Collections.synchronizedList返回的线程安全的List内部使用的锁是哪个对象,所以你得看看Collections.synchronizedList这个方法的源码了。该方法源码如下:
-
public static <T> List<T> synchronizedList(List<T> list) {
-
return (list instanceof RandomAccess ?
-
new SynchronizedRandomAccessList<T>(list) :
-
new SynchronizedList<T>(list));
-
}
通过源码,我们还需要知道ArrayList是否实现了RandomAccess接口:
-
public class ArrayList<E> extends AbstractList<E>
-
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
查看ArrayList的源码,可以看到它实现了RandomAccess,所以上面的synchronizedList放回的应该是SynchronizedRandomAccessList的实例。接下来看看SynchronizedRandomAccessList这个类的实现:
-
static class SynchronizedRandomAccessList<E>
-
extends SynchronizedList<E>
-
implements RandomAccess {
-
-
SynchronizedRandomAccessList(List<E> list) {
-
super(list);
-
}
-
-
SynchronizedRandomAccessList(List<E> list, Object mutex) {
-
super(list, mutex);
-
}
-
-
public List<E> subList(int fromIndex, int toIndex) {
-
synchronized(mutex) {
-
return new SynchronizedRandomAccessList<E>(
-
list.subList(fromIndex, toIndex), mutex);
-
}
-
}
-
-
static final long serialVersionUID = 1530674583602358482L;
-
-
/**
-
* Allows instances to be deserialized in pre-1.4 JREs (which do
-
* not have SynchronizedRandomAccessList). SynchronizedList has
-
* a readResolve method that inverts this transformation upon
-
* deserialization.
-
*/
-
private Object writeReplace() {
-
return new SynchronizedList<E>(list);
-
}
-
}
因为SynchronizedRandomAccessList这个类继承自SynchronizedList,而大部分方法都在SynchronizedList中实现了,所以源码中只包含了很少的方法,但是通过subList方法,我们可以看到这里使用的锁对象为mutex对象,而mutex是在SynchronizedCollection类中定义的,所以再看看SynchronizedCollection这个类中关于mutex的定义部分源码:
-
static class SynchronizedCollection<E> implements Collection<E>, Serializable {
-
// use serialVersionUID from JDK 1.2.2 for interoperability
-
private static final long serialVersionUID = 3053995032091335093L;
-
-
final Collection<E> c; // Backing Collection
-
final Object mutex; // Object on which to synchronize
-
-
SynchronizedCollection(Collection<E> c) {
-
if (c==null)
-
throw new NullPointerException();
-
this.c = c;
-
mutex = this;
-
}
-
SynchronizedCollection(Collection<E> c, Object mutex) {
-
this.c = c;
-
this.mutex = mutex;
-
}
-
}
可以看到mutex就是当前的SynchronizedCollection对象,而SynchronizedRandomAccessList继承自SynchronizedList,SynchronizedList又继承自SynchronizedCollection,所以SynchronizedRandomAccessList中的mutex也就是SynchronizedRandomAccessList的this对象。所以在GoodListHelper中使用的锁list对象,和SynchronizedRandomAccessList内部的锁是一致的,所以它可以实现线程安全性。
java 多线程操作List,已经做了同步synchronized,还会有ConcurrentModificationException,知道为什么吗?
如题,最近项目里有个模块我做了异步处理方面的事情,在code过程中发现一个颠覆我对synchronized这个关键字和用法的地方,请问各位java开发者们是否对此有一个合理的解释,不多说,我直接贴出问题代码:
(事实证明这是一个坑,各位读者,如果有兴趣,可以先不看答案,自己看看能不能发现这个坑)
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class ConcurrentList { //private static List<String> TEST_LIST = new CopyOnWriteArrayList<String>(); private static List<String> TEST_LIST = Collections.synchronizedList(new ArrayList<String>()); public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (TEST_LIST) { TEST_LIST.add("11"); } System.out.println("Thread1 running"); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (TEST_LIST) { for (String at : TEST_LIST) { TEST_LIST.add("22"); } } System.out.println("Thread2 running"); } } }).start(); } }
输出结果是:
Thread1 running Exception in thread "Thread-1" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372) at java.util.AbstractList$Itr.next(AbstractList.java:343) at com.free4lab.lol.ConcurrentList$2.run(ConcurrentList.java:40) at java.lang.Thread.run(Thread.java:619) Thread1 running Thread1 running Thread1 running Thread1 running Thread1 running Thread1 running Thread1 running Thread1 running
-----------------------------------分隔线,以下是解释--------------------------------
问题明了了:
以上问题不是并发的问题,是ArrayList的问题,是个坑!且看如下代码,以及运行结果:
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class ConcurrentList { //private static List<String> TEST_LIST = new CopyOnWriteArrayList<String>(); private static List<String> TEST_LIST = Collections.synchronizedList(new ArrayList<String>()); public static void main(String[] args) { TEST_LIST.add("111"); TEST_LIST.add("222"); for (String at : TEST_LIST) { System.out.println(at); TEST_LIST.add("333"); System.out.println("add over"); } } }
结果是:
111 add over Exception in thread "main" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372) at java.util.AbstractList$Itr.next(AbstractList.java:343) at com.free4lab.lol.ConcurrentList.main(ConcurrentList.java:15)
分析:我们发现迭代了一次之后就抛出所谓的并发修改异常,不过这里没有多线程,看下源代码就知道了
list.add的时候执行了,修改了modCount,循环外面一次add到第一次迭代不会有问题,因为初始化的时候在AbstractList中int expectedModCount = modCount;,
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = e; return true; } public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } }
public E next() { checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } }
这样迭代器next()第一次 checkForComodification() 是不会抛出异常的,第二次才会抛出异常,因为在checkForComodification()里检查了
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
这样,在循环迭代中,进行了一次add操作,修改了modcount变量,再次迭代的时候,异常就throw出来了!
如果非要进行这样的操作,那么声明list为CopyOnWriteArrayList,就ok!因为用了copyonwrite技术
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class ConcurrentList { private static List<String> TEST_LIST = new CopyOnWriteArrayList<String>(); //private static List<String> TEST_LIST = Collections.synchronizedList(new ArrayList<String>()); public static void main(String[] args) { TEST_LIST.add("111"); TEST_LIST.add("222"); for (String at : TEST_LIST) { System.out.println(at); TEST_LIST.add("333"); System.out.println("add over"); } } }
输出是正确的:
111 add over 222 add over
额外再说一点,也可以用iterator迭代,不过同样也无法调用next()方法(我注释掉了),这样程序就是死循环了,不断的加,不断的迭代。所以我感觉如果需要在迭代中增加元素,真正有用的还是CopyOnWriteArrayList,不过实际中,如果CopyOnWriteArrayList代价太高,可能我们可以申请一个临时list存放,在迭代后合并到主list中!
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class ConcurrentList { //private static List<String> TEST_LIST = new CopyOnWriteArrayList<String>(); private static List<String> TEST_LIST = Collections.synchronizedList(new ArrayList<String>()); public static void main(String[] args) { TEST_LIST.add("111"); TEST_LIST.add("222"); Iterator iterator = TEST_LIST.iterator(); while(iterator.hasNext()){ //System.out.println(iterator.next()); TEST_LIST.add("333"); System.out.println("add over"); } } }