Java集合并发安全面试题

news/2025/2/26 2:38:36/

Java集合并发安全面试题

同步包装器

Q1: Collections的同步包装器是如何实现线程安全的?

java">public class SynchronizedWrapperExample {// 1. 基本使用public void demonstrateSynchronizedCollections() {// 创建同步ListList<String> syncList = Collections.synchronizedList(new ArrayList<>());// 创建同步SetSet<String> syncSet = Collections.synchronizedSet(new HashSet<>());// 创建同步MapMap<String, String> syncMap = Collections.synchronizedMap(new HashMap<>());// 正确的遍历方式synchronized (syncList) {Iterator<String> iterator = syncList.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}}}// 2. 同步包装器的实现原理public class SimpleSynchronizedList<E> {private final List<E> list;private final Object mutex;public SimpleSynchronizedList(List<E> list) {this.list = list;this.mutex = this;}public boolean add(E e) {synchronized (mutex) {return list.add(e);}}public E get(int index) {synchronized (mutex) {return list.get(index);}}public E remove(int index) {synchronized (mutex) {return list.remove(index);}}}
}

并发集合类

Q2: ConcurrentHashMap的实现原理是什么?

java">public class ConcurrentHashMapExample {// 1. 基本使用public void demonstrateConcurrentHashMap() {ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();// 原子操作map.put("A", 1);map.putIfAbsent("B", 2);map.replace("A", 1, 3);// 并发迭代for (Map.Entry<String, Integer> entry : map.entrySet()) {// 迭代时可以修改,不会抛出ConcurrentModificationExceptionmap.put("C", 3);}}// 2. 常见使用场景public class ConcurrentCounterExample {private ConcurrentHashMap<String, AtomicInteger> counters = new ConcurrentHashMap<>();public void incrementCounter(String key) {counters.computeIfAbsent(key, k -> new AtomicInteger(0)).incrementAndGet();}public int getCount(String key) {AtomicInteger counter = counters.get(key);return counter == null ? 0 : counter.get();}}
}

Q3: CopyOnWriteArrayList的使用场景是什么?

java">public class CopyOnWriteArrayListExample {// 1. 基本使用public void demonstrateCopyOnWrite() {CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();// 写操作会复制整个数组list.add("A");list.add("B");// 读操作不会阻塞for (String item : list) {System.out.println(item);// 迭代时修改不会抛出异常list.add("C");}}// 2. 事件监听器列表public class EventListenerRegistry {private final CopyOnWriteArrayList<EventListener> listeners = new CopyOnWriteArrayList<>();public void addEventListener(EventListener listener) {listeners.add(listener);}public void removeEventListener(EventListener listener) {listeners.remove(listener);}public void fireEvent(Event event) {for (EventListener listener : listeners) {listener.onEvent(event);}}}
}

阻塞队列

Q4: 阻塞队列的实现类有哪些?它们的特点是什么?

java">public class BlockingQueueExample {// 1. ArrayBlockingQueue示例public void demonstrateArrayBlockingQueue() {ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);// 生产者线程new Thread(() -> {try {queue.put("A");  // 队列满时阻塞queue.put("B");queue.put("C");queue.put("D");  // 阻塞直到有空间} catch (InterruptedException e) {Thread.currentThread().interrupt();}}).start();// 消费者线程new Thread(() -> {try {String item = queue.take();  // 队列空时阻塞System.out.println("Consumed: " + item);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}).start();}// 2. 生产者-消费者模式public class ProducerConsumerExample {private final BlockingQueue<Task> taskQueue;public ProducerConsumerExample(int capacity) {this.taskQueue = new LinkedBlockingQueue<>(capacity);}public void produce(Task task) throws InterruptedException {taskQueue.put(task);}public Task consume() throws InterruptedException {return taskQueue.take();}// 工作线程public void startWorker() {new Thread(() -> {while (!Thread.currentThread().isInterrupted()) {try {Task task = consume();task.process();} catch (InterruptedException e) {Thread.currentThread().interrupt();break;}}}).start();}}
}

并发安全策略

Q5: 如何选择合适的并发集合类?

java">public class ConcurrentCollectionSelectionExample {// 1. 不同场景的选择public void demonstrateSelection() {// 高并发读取场景ConcurrentHashMap<String, String> concurrentMap = new ConcurrentHashMap<>();// 读多写少场景CopyOnWriteArrayList<String> copyOnWriteList = new CopyOnWriteArrayList<>();// 生产者-消费者场景BlockingQueue<Task> blockingQueue = new LinkedBlockingQueue<>();// 需要线程安全的有序集合ConcurrentSkipListMap<String, String> skipListMap = new ConcurrentSkipListMap<>();}// 2. 性能对比public void performanceComparison() {// 同步MapMap<String, String> syncMap = Collections.synchronizedMap(new HashMap<>());// 并发MapConcurrentHashMap<String, String> concurrentMap = new ConcurrentHashMap<>();// 多线程测试Runnable syncMapTest = () -> {for (int i = 0; i < 1000; i++) {syncMap.put("key" + i, "value" + i);}};Runnable concurrentMapTest = () -> {for (int i = 0; i < 1000; i++) {concurrentMap.put("key" + i, "value" + i);}};// 执行测试并比较性能}
}

Q6: 如何实现自定义的线程安全集合?

java">public class CustomThreadSafeCollectionExample {// 1. 使用synchronized关键字public class SynchronizedList<E> {private final List<E> list = new ArrayList<>();public synchronized boolean add(E element) {return list.add(element);}public synchronized E get(int index) {return list.get(index);}public synchronized boolean remove(E element) {return list.remove(element);}}// 2. 使用ReentrantReadWriteLockpublic class ReadWriteList<E> {private final List<E> list = new ArrayList<>();private final ReadWriteLock lock = new ReentrantReadWriteLock();private final Lock readLock = lock.readLock();private final Lock writeLock = lock.writeLock();public boolean add(E element) {writeLock.lock();try {return list.add(element);} finally {writeLock.unlock();}}public E get(int index) {readLock.lock();try {return list.get(index);} finally {readLock.unlock();}}}// 3. 使用StampedLockpublic class StampedList<E> {private final List<E> list = new ArrayList<>();private final StampedLock lock = new StampedLock();public boolean add(E element) {long stamp = lock.writeLock();try {return list.add(element);} finally {lock.unlockWrite(stamp);}}public E get(int index) {long stamp = lock.tryOptimisticRead();E value = list.get(index);if (!lock.validate(stamp)) {stamp = lock.readLock();try {value = list.get(index);} finally {lock.unlockRead(stamp);}}return value;}}
}

面试关键点

  1. 理解同步包装器的实现原理
  2. 掌握ConcurrentHashMap的特性
  3. 了解CopyOnWriteArrayList的应用场景
  4. 熟悉阻塞队列的使用方式
  5. 掌握不同并发集合的选择标准
  6. 理解读写锁的使用场景
  7. 能够实现自定义线程安全集合
  8. 注意并发集合的性能影响

http://www.ppmy.cn/news/1574935.html

相关文章

fpga助教面试题

第一题 module sfp_pwm( input wire clk, //clk is 200M input wire rst_n, input wire clk_10M_i, input wire PPS_i, output reg pwm ) reg [6:0] cunt ;always (posedge clk ) beginif(!rst_n)cunt<0;else if(cunt19) //200M是10M的20倍cunt<0;elsecunt<cunt1;…

DeepSeek为云厂商带来新机遇,东吴证券看好AI带动百度智能云增长

近日&#xff0c;摩根士丹利&#xff08;亚洲&#xff09;发布研究报告《DeepSeek-Al Bifurcation》&#xff0c;报告指出DeepSeek的爆火催生了低成本人工智能市场&#xff0c;为数据中心、芯片及云服务提供商带来新的发展机遇。 同时&#xff0c;东吴证券发布研究报告维持百度…

Python 学习之旅:高级阶段(十六)Web 开发之路由和视图函数

在 Python 的 Web 开发领域,路由和视图函数是构建 Web 应用不可或缺的部分。它们就像是 Web 应用的 “交通枢纽” 和 “服务窗口”,路由负责引导用户请求到达正确的处理地点,而视图函数则负责处理这些请求并返回相应的响应。接下来,我们将以 Flask 框架为例,深入了解路由和…

Oracle 深入理解Lock和Latch ,解析访问数据块全流程

Oracle 锁机制介绍 根据保护对象的不同&#xff0c;单实例Oracle数据库锁可以分为以下几大类&#xff1a; DML lock&#xff08;data locks&#xff0c;数据锁&#xff09;&#xff1a;用于保护数据的完整性&#xff1b; DDL lock&#xff08;dictionary locks&#xff0c;字典…

去耦电容的作用详解

在霍尔元件的实际应用过程中&#xff0c;经常会用到去耦电容。去耦电容是电路中装设在元件的电源端的电容&#xff0c;其作用详解如下&#xff1a; 一、基本概念 去耦电容&#xff0c;也称退耦电容&#xff0c;是把输出信号的干扰作为滤除对象。它通常安装在集成电路&#xf…

天 锐 蓝盾终端安全管理系统:办公U盘拷贝使用管控限制

天 锐 蓝盾终端安全管理系统以终端安全为基石&#xff0c;深度融合安全、管理与维护三大要素&#xff0c;通过对桌面终端系统的精准把控&#xff0c;助力企业用户构筑起更为安全、稳固且可靠的网络运行环境。它实现了管理的标准化&#xff0c;有效破解终端安全管理难题&#xf…

http 协议和 https 协议的区别是什么?

互联网各领域资料分享专区(不定期更新): Sheet 正文 HTTP(超文本传输协议)和 HTTPS(安全超文本传输协议)的核心区别在于安全性,以下是两者的主要对比: 1. 协议与安全性 HTTP:数据以明文形式传输,易被窃听、篡改或中间人攻击。HTTPS:通过 SSL/TLS 协议对数据进行加密…

《2025国内免费DeepSeek-R1自部署平台实测指南:三大运营商/腾讯/华为哪家强?附避坑清单》

更新日期&#xff1a;2025年2月24日 | 实测时效性声明&#xff1a;部分服务可能因政策调整限流或下线&#xff0c;建议结合最新信息参考。 一、前言&#xff1a;为什么关注DeepSeek-R1自部署&#xff1f; DeepSeek-R1-671B作为国内首个千亿级开源模型&#xff0c;其“满血版”…