MergeMap.java
package org.microspace.event;
import java.util.HashMap;
/*
* A map to store the latest TakeTask.
* <p>
* MessageIds are unique in each message class.
*
* @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
* @version 2016-06-26
*/
public class MergeMap<T> {
HashMap<Class<?>, HashMap<Object, TakeTask<T, ?>>> map = new HashMap<>(512, 0.6f);
/**
* Get the latest task.
* @param task The task with a messageId.
* @return The latest task.
*/
public TakeTask<T, ?> get(TakeTask<T, ?> task) {
return get (task.getMessage().getClass(), task.getMessageId());
}
/**
* Get the latest task.
* @param cl The message class.
* @param key The messageId
* @return The latest task.
*/
public TakeTask<T, ?> get(Class<?> cl, Object key) {
HashMap<Object, TakeTask<T, ?>> m = map.get(cl);
if (m == null) return null;
return m.get(key);
}
/**
* Remove the latest task.
* @param task The pattern with a messageId.
* @return The latest task.
*/
public TakeTask<T, ?> remove(TakeTask<T, ?> task) {
return remove (task.getMessage().getClass(), task.getMessageId());
}
/**
* Remove the latest task.
* @param cl The message class.
* @param key The messageId
* @return The latest task.
*/
public TakeTask<T, ?> remove(Class<?> cl, Object key) {
HashMap<Object, TakeTask<T, ?>> m = map.get(cl);
if (m == null) return null;
return m.remove(key);
}
/**
* Store the latest task.
* @param task The task that will overwrite the latest task.
* @return The old task.
*/
public TakeTask<T, ?> put(TakeTask<T, ?> task) {
Class<?> cl = task.getMessage().getClass();
Object key = task.getMessageId();
HashMap<Object, TakeTask<T, ?>> m = map.get(cl);
if (m == null) {
m = new HashMap<>(512, 0.6f);
map.put(cl, m);
}
return m.put(key, task);
}
/**
* Query the latest images.
* @return The full size of this map.
*/
public int size () {
int retVle = 0;
for (HashMap<Object, TakeTask<T, ?>> m : map.values()) {
retVle += m.size();
}
return retVle;
}
/**
* Clear all maps.
*/
public void clear() {
map.clear();
}
}