模仿LinkedHashMap 实现一个线程安全的ConcurrentLinkedHashMap,
使用CopyOnWriteArrayList和ConcurrentHashMap来实现
使用场景是:项目中需要保证Map中的数据按顺序存放,一开始想到LinkedHashMap,但是
LinkedHashMap 线程不安全,所以自己实现了一个。
后面需要遍历map的时候,只需要遍历map.getKeyList(),拿到所有顺序的key就行了
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* 模仿LinkedHashMap 实现一个线程安全的ConcurrentLinkedHashMap,使得ConcurrentLinkedHashMap中的数据按顺序遍历,怎么存放就怎么取
* @param <K>
* @param <V>
*/
public class ConcurrentLinkedHashMap<K, V> extends ConcurrentHashMap<K, V> {
/**
* keyList 用于存放key的顺序
*/
private final CopyOnWriteArrayList<K> keyList = new CopyOnWriteArrayList<>();
@Override
public V put(K key, V value) {
//如果在map中不存在,就加入list 集合
if (!containsKey(key)) {
keyList.add(key);
}
return super.put(key, value);
}
public CopyOnWriteArrayList<K> getKeyList() {
return new CopyOnWriteArrayList<>(keyList);
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
ConcurrentLinkedHashMap<String,String> map=new ConcurrentLinkedHashMap();
map.put("333","333");
map.put("555","555");
map.put("111","111");
map.put("是是是","是是是");
System.out.format("打印map中经过hash后的顺序:%s%n",map);
System.out.format("打印map中key的顺序:%s%n",map.getKeyList());
System.out.println("遍历:使得ConcurrentLinkedHashMap中的数据按顺序遍历,怎么存放就怎么取");
for (String key : map.getKeyList()) {
System.out.format("key = %s,value =%s%n",key,map.get(key));
}
//结果:
//打印map中经过hash后的顺序:{111=111, 333=333, 是是是=是是是, 555=555}
//打印map中key的顺序:[333, 555, 111, 是是是]
//遍历:使得ConcurrentLinkedHashMap中的数据按顺序遍历,怎么存放就怎么取
//key = 333,value =333
//key = 555,value =555
//key = 111,value =111
//key = 是是是,value =是是是
}
}
171万+






