我想正确设置一个服务器端缓存,我正在寻找建设性的批评,我目前的设置。缓存在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