Java
1.容器的同步控制: 多線程并發訪問集合的線程安全
- 常用容器
ArrayList
HashSet
HashMap
等都是線程不安全的 -
Collections
提供了synchronizedXxx()
方法,將指定容器包裝成同步synchronizedList
synchronizedSet
synchronizedMap
public void test1() {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
// 可以同步
List<String> list1 = Collections.synchronizedList(list);
}
2.不可變設置:"只讀訪問",Collections
提供了三種方法
-
emptyXxx()
空的不可變的集合 -
singletonXxx()
一個元素不可變的集合 -
unmodifiableXxx()
不可修改的容器
public void test1() {
Map<String,String> map = new HashMap<>();
map.put("a","a");
map.put("b","b");
// 只允許讀
Map<String,String> map1 = Collections.unmodifiableMap(map);
}
public static Set<String> oper(Set<String> set) {
if (set == null) {
return Collections.EMPTY_SET; // 外部獲取避免空對象
}
return set;
}