今天看java并发编程时,发现一段有趣的代码。顺便记记笔记。
@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; } }
不仔细的看,还以为这个类是线程安全的,因为putIfAbsent方法加了synchronized。不过细心的同学就会发现原来putIfAbsent方法和List并不是使用的同一个锁对象,List使用的锁对象并不是BadListHelper,而是list。假如A线程进入putIfAbsent方法,list这个锁并没有被获取(A线程获取的是 BadListHelper这个对象),所以其他线程还能够获得list锁对象来改变list对象。boolean absent = !list.contains(x);当线程到这串代码结束时,其他线程获得list锁对象,从而就能调用list的方法来改变list对象,这时候就可能导致!list.contains(x)改变,即域absent并不是A线程得到的布尔类型。所以这个类并不是线程安全的。
正确的代码
@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,其自身具备的方法可以同步,其自身不具备的方法,需要手动同步,另外就是 iterator()方法也需要我们手动加上同步操作.