不安全示例
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for(int i=0 ;i <10;i++){
new Thread(()->{
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(10));
list.add(UUID.randomUUID().toString().substring(0,8));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list);
},String.valueOf(i)).start();
}
list.forEach(System.out::println);
}
解决
写时复制
写时复制的设计初衷是优先保证读的效率
因此,基于读写分离的思路,读的时候不加锁
为了保证读的安全(防止读时写),需要将写操作的生效变为一瞬间
这通过类似下面流程实现
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
写时复制的限制
不安全示例
同 List ,集合改为 HashSet 即可
// Dummy value to associate with an Object in the backing Map
// 删元素时,返回元素值,因此默认值不是 null 以区分是否删成功
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
写时复制
//1 查重
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
addIfAbsent(e, snapshot);
}
private boolean addIfAbsent(E e, Object[] snapshot) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] current = getArray();
int len = current.length;
if (snapshot != current) {
// 防止查重时,其他线程操作
// 先判断新旧 set 的前半截得一致,后判断另一个线程是否塞了和当前值一样的值进去
// Optimize for lost race to another addXXX operation
int common = Math.min(snapshot.length, len);
for (int i = 0; i < common; i++)
if (current[i] != snapshot[i] && eq(e, current[i]))
return false;
if (indexOf(e, current, common, len) >= 0)
return false;
}
Object[] newElements = Arrays.copyOf(current, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
不安全示例
略
写时复制