2013-08-23 39 views
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的多個實例(數百個)?

回答

0

是的,它確實創建了一個MethodMetricsHandler對象的緩存。這種方法通常並不壞,但如果你描述了你的用例,我可能會說更多,因爲這個解決方案非常不尋常。你已經部分改造了工廠模式。

想想也提出了一些建議:

  • 這是非常奇怪的是,你需要運行getHandler
  • 作爲「配置」之前調用3所制定者是不是關鍵,你會得到相同的對象針對不同配置以及相同的目標類別和方法緩存
  • 爲什麼targetClass是Object。您可能想改爲通過Class<?>
  • 你打算從緩存中驅逐對象嗎?
+0

我知道非常獨特和奇怪的情況。每次在應用程序中調用類時,庫基本上都會檢查類元數據。緩存將在應用程序的整個生命週期內存活,因此可能有n個調用,因此如果我不緩存,則爲n MethodMetricsHandler對象。進入MethodMetricsHandler實例的類無法更改。不過,我發現setter有問題,因爲這將在多線程環境中運行。有關設計更改的任何建議以使其線程安全? – MWright