我有以下代码。如何使其线程安全?
public interface Stub {
public void subscribe(String key);
public void unsubscribe(String key);
}
public interface Listener {
public void onEvent(String key, String event);
}
public class StubTest {
Stub stub;
ConcurrentHashMap<String,ConcurrentSkipListSet<Listener>> map = new ConcurrentHashMap<>();
public void addListener(String key, Listener listener){
if(map.containsKey(key)){
map.get(key).add(listener);
}else{
ConcurrentSkipListSet<Listener> lst = new ConcurrentSkipListSet<>();
lst.add(listener);
map.put(key,lst);
}
}
public void removeListener(String key, Listener listener){
if(map.contains(key)){
Set<Listener> lst = map.get(key);
lst.remove(listener);
if(lst.size() <= 0) map.remove(key);
}
}
public void publish(String key, String event){
Set<Listener> lst = map.get(key);
if(lst != null){
lst.stream().forEach(l -> l.onEvent(key,event));
}
}
}
正如人们可以看到地图中有很多状态维护但是我愿意完全重写代码以保持任何状态。可能正在使用java 8的功能结构?