我想正確設置一個服務器端緩存,我正在尋找建設性的批評,我目前的設置。緩存在Servlet啓動時加載並且再也不會更改,所以實際上它是一個只讀緩存。它顯然需要留在內存中的Servlet的生命週期。以下是我把它設置正確設置一個簡單的服務器端緩存
private static List<ProductData> _cache;
private static ProductManager productManager;
private ProductManager() {
try {
lookup();
} catch (Exception ex) {
_cache = null;
}
}
public synchronized static ProductManager getInstance() {
if (productManager== null) {
productManager= new ProductManager();
}
return productManager;
}
緩存是由Servlet設置如下:
private ProductManager productManager;
public void init(ServletConfig config) throws ServletException {
productManager = ProductManager.getInstance();
}
最後,這是我訪問:
public static ProductData lookup(long id) throws Exception {
if (_cache != null) {
for (int i = 0; i < _cache.size(); i++) {
if (_cache.get(i).id == id) {
return _cache.get(i);
}
}
}
// Look it up in the DB.
}
public static List<ProductData> lookup() throws Exception {
if (_cache != null) {
return _cache;
}
// Read it from the DB.
_cache = list;
return list;
}
如何,特別是,我應該去了解線程
您在web.xml
註冊如下安全?同步塊和/或併發集合類? – bluedevil2k 2010-08-23 21:38:35
併發集合不會對您有所幫助,因爲我相信您正在加載緩存一次,在此之後它不會更改。第二個'lookup'方法 - 實際上加載緩存 - 需要被「同步」。否則兩個線程都會發現'_cache'是'null',可能都會嘗試從數據庫加載。 – 2010-08-28 21:21:52