com.feingto.iot.common.model.CacheMap Maven / Gradle / Ivy
package com.feingto.iot.common.model;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* 封装 MultipleConcurrentHashMap
* key为数组
*
* @author longfei
**/
public class CacheMap {
private ConcurrentHashMap> map = new ConcurrentHashMap<>();
private Node buildOne(K k, V v) {
Node node = new Node<>(k);
node.putNextValue(k, v);
return node;
}
public List get(K[] ks) {
if (ks.length == 1) {
return map.get(ks[0]).get();
} else {
Node node = map.get(ks[0]);
if (node != null) {
List all = new ArrayList<>(node.get());
for (int i = 1; i < ks.length; i++) {
node = node.getNext(ks[i]);
if (node == null) {
break;
}
all.addAll(node.get());
}
return all;
}
return null;
}
}
public boolean put(K[] topic, V v) {
if (topic.length == 1) {
Node kvNode = buildOne(topic[0], v);
if (kvNode != null && kvNode.getTopic().equals(topic[0])) {
return true;
}
} else {
Node kvNode = buildOne(topic[0], null);
for (int i = 1; i < topic.length; i++) {
kvNode = (i == topic.length - 1)
? kvNode.putNextValue(topic[i], v)
: kvNode.putNextValue(topic[i], null);
}
}
return true;
}
public boolean remove(K[] ks, V v) {
if (ks.length == 1) {
return map.get(ks[0]).delValue(v);
} else {
Node kvNode = map.get(ks[0]);
for (int i = 1; i < ks.length && kvNode != null; i++) {
kvNode = kvNode.getNext(ks[i]);
}
assert kvNode != null;
return kvNode.delValue(v);
}
}
class Node {
private final H topic;
private volatile ConcurrentHashMap> map = new ConcurrentHashMap<>();
List vs = new CopyOnWriteArrayList<>();
Node(H topic) {
this.topic = topic;
}
H getTopic() {
return topic;
}
private boolean delValue(T v) {
return vs.remove(v);
}
private Node putNextValue(H k, T v) {
Node kvNode = map.computeIfAbsent(k, key -> new Node<>(k));
if (v != null) {
kvNode.put(v);
}
return kvNode;
}
private Node getNext(H k) {
return map.get(k);
}
private void put(T v) {
vs.add(v);
}
private List get() {
return vs;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy