J.U.C
- 其实就是JDK提供的一个包:java.util.concurrent
CopyOnWriteArrayList
- 相较于ArrayList,CopyOnWriteArrayList是线程安全的;
- 在添加新元素时,先将数组拷贝一份,在新数组中写,写完在把引用指向新数组;
- CopyOnWriteArrayList的add操作是在锁的保护下进行的;
- 读操作是在原数组上进行的,不需要加锁;
CopyOnWriteArrayList缺点
- 写操作时复制数组,消耗内存;
- 不能用于实时读的场景,在多线程情况下,可能读到落后的数据,写期间允许读;
- 在频繁的写操作时慎用,在高性能互联网应用中,很容易引起故障;
通常,共享的List不会很大,修改的情况也会很少,CopyOnWriteArrayList可以代替ArrayList满足线程安全的要求;
CopyOnWriteArrayList示例
import com.example.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
@Slf4j
@ThreadSafe
public class CopyOnWriteArrayListExample {
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程数
public static int threadTotal = 200;
private static List<Integer> list = new CopyOnWriteArrayList<>();
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) {
final int count = i;
executorService.execute(() -> {
try {
semaphore.acquire();
update(count);
semaphore.release();
} catch (Exception e) {
log.error("exception", e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("size:{}", list.size());
}
private static void update(int i) {
list.add(i);
}
}
输出:
13:59:46.178 [main] INFO com.example.concurrency.example.concurrent.CopyOnWriteArrayListExample - size:5000