0
我正在使用guava-libraries LoadingCache來緩存我的應用中的類。使用guava-libraries LoadingCache來緩存java pojo
這是我想出的課程。
public class MethodMetricsHandlerCache {
private Object targetClass;
private Method method;
private Configuration config;
private LoadingCache<String, MethodMetricsHandler> handlers = CacheBuilder.newBuilder()
.maximumSize(1000)
.build(
new CacheLoader<String, MethodMetricsHandler>() {
public MethodMetricsHandler load(String identifier) {
return createMethodMetricsHandler(identifier);
}
});
private MethodMetricsHandler createMethodMetricsHandler(String identifier) {
return new MethodMetricsHandler(targetClass, method, config);
}
public void setTargetClass(Object targetClass) {
this.targetClass = targetClass;
}
public void setMethod(Method method) {
this.method = method;
}
public void setConfig(Configuration config) {
this.config = config;
}
public MethodMetricsHandler getHandler(String identifier) throws ExecutionException {
return handlers.get(identifier);
}
我使用這個類,如下所示緩存MethodMetricsHandler
...
private static MethodMetricsHandlerCache methodMetricsHandlerCache = new MethodMetricsHandlerCache();
...
MethodMetricsHandler handler = getMethodMetricsHandler(targetClass, method, config);
private MethodMetricsHandler getMethodMetricsHandler(Object targetClass, Method method, Configuration config) throws ExecutionException {
String identifier = targetClass.getClass().getCanonicalName() + "." + method.getName();
methodMetricsHandlerCache.setTargetClass(targetClass);
methodMetricsHandlerCache.setMethod(method);
methodMetricsHandlerCache.setConfig(config);
return methodMetricsHandlerCache.getHandler(identifier);
}
我的問題:
這是創建鍵上標識MethodMetricHandler類的高速緩存(未以前那麼用這個只是一個完整的檢查)。
還有更好的方法嗎?鑑於如果我不緩存,我將有一個給定標識符的同一個MethodMetricHandler的多個實例(數百個)?
我知道非常獨特和奇怪的情況。每次在應用程序中調用類時,庫基本上都會檢查類元數據。緩存將在應用程序的整個生命週期內存活,因此可能有n個調用,因此如果我不緩存,則爲n MethodMetricsHandler對象。進入MethodMetricsHandler實例的類無法更改。不過,我發現setter有問題,因爲這將在多線程環境中運行。有關設計更改的任何建議以使其線程安全? – MWright