1、使用List时的加锁代码
不安全的代码:
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;
}
}
但使用synchronized声明的方法锁住的是调用该方法的对象,而不是提供方法的对象。
所以上例的代码中,list对象并没有被锁住,如果有其他方法也是有相同的判断为空即添加的代码,就可能重复添加了。
正确的写法:
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;
}
}
}