AccessorCache.java
package org.microspace.util;
import java.util.HashMap;
import java.util.Map;
import org.microspace.space.AccessorGenerator;
import org.microspace.space.SpaceConfig;
import org.microspace.table.column.Accessor;
/**
* AccessorCache is caching accessors in a thread.
*
* @author Gaspar Sinai - {@literal gaspar.sinai@microspace.org}
* @version 2016-06-26
*/
public class AccessorCache {
final static MicroLogger log = new MicroLogger (AccessorCache.class);
final ThreadLocal<HashMap<String, Accessor<?>>> accessorRepo = new ThreadLocal<HashMap<String, Accessor<?>>> () {
@Override
protected HashMap<String, Accessor<?>> initialValue() {
return new HashMap<String, Accessor<?>>();
}
};
final AccessorGenerator accessorGenerator;
public AccessorCache (SpaceConfig config) {
accessorGenerator = config.getAccessGenerator();
}
public AccessorCache (AccessorGenerator accessorGenerator) {
this.accessorGenerator = accessorGenerator;
}
public Map<String, Accessor<?>> list () {
return Economical.unmodifiableMap(accessorRepo.get());
}
public Accessor<?> get (String className) {
Accessor<?> accessor = accessorRepo.get().get(className);
if (accessor != null) {
return accessor;
}
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException cnf) {
log.error("getAccessor error", cnf);
}
accessor = accessorGenerator.newAccessor(clazz);
accessorRepo.get().put(className, accessor);
return accessor;
}
@SuppressWarnings("unchecked")
public <T> Accessor<T> get (Class<T> clazz) {
return (Accessor<T>) get (clazz.getName());
}
}