总结
保证线程安全的方式:synchronized,ReentrantLock ,CAS
Map
- HashTable
Map<String,String> hashtable= new Hashtable<>() ;
hashtable.put("key","value");
a. 如何保证线程安全?synchronized
b. 为NULL 会发生什么?key和value 为null都会 NullPointerException
c. 扩容?扩容为原来的2倍+1
- ConcurrentHashMap
Map<String,String> concurrentHashMap= new ConcurrentHashMap<>();
concurrentHashMap.put("key","value");
a. 如何保证线程安全?CAS + synchronized
b. 为NULL 会发生什么?key和value 为null都会 NullPointerException
c. 扩容大小?扩容为原来的2倍
d. 扩容步骤:待补充
- Collections.synchronizedMap
Map<String,String> objectObjectMap = Collections.synchronizedMap(new HashMap<>());
objectObjectMap.put("key","value");
a. 如何保证线程安全?synchronized
b. 为NULL 会发生什么?key和value 都可以为null.因为用的是 HashMap
c. 扩容?扩容为原来的2倍
d. 扩容步骤:待补充
List
- CopyOnWriteArrayList
List<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
copyOnWriteArrayList.add("str1");
a. 如何保证线程安全?ReentrantLock
b. 扩容:Arrays.copyOf新生成长度+1的Array添加返回
- Vector
List<String> vector = new Vector<>();
vector.add("str1");
a. 如何保证线程安全?synchronized
b. 扩容:默认长度是10 ,超了后 2倍;
代码:
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?capacityIncrement :oldCapacity);
- Collections.synchronizedList
List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());
synchronizedList.add("str2");
a. 如何保证线程安全?synchronized
c. 扩容?扩容为原来的1.5倍(这里用的是ArrayList)
Set
Set<String> copyOnWriteArraySet = new CopyOnWriteArraySet<>();
copyOnWriteArraySet.add("str1");
// a. 如何保证线程安全?ReentrantLock
Set<String> synchronizedSet = Collections.synchronizedSet(new HashSet<>());
synchronizedSet.add("str2");
// a. 如何保证线程安全?synchronized
Queue
Queue<String> queue = new ConcurrentLinkedDeque<>();
queue.offer("queue");
// null 空指针
// CAS 保证线程安全
// 非阻塞队列
Queue<String> blockingQueue = new LinkedBlockingQueue<>();
blockingQueue.offer("queue");
// ReentrantLock 保证线程安全
// null 空指针
// 阻塞队列