現在、私は HashMap を実装しています
private static Map<String, Item> cached = new HashMap<String, Item>();
Item はプロパティ Date expireTime および byte[] データを持つオブジェクトです
このマップは、複数のスレッドが同時にヒットし始めたときに使用されます。私が行うチェックは
1.
public static final byte[] getCachedData(HttpServletRequest request) throws ServletException
{
String url = getFullURL(request);
Map<String, Item> cache = getCache(request); // this chec
Item item = null;
synchronized (cache)
{
item = cache.get(url);
if (null == item)
return null;
// Make sure that it is not over an hour old.
if (item.expirationTime.getTime() < System.currentTimeMillis())
{
cache.remove(url);
item = null;
}
}
if (null == item)
{
log.info("Expiring Item: " + url);
return null;
}
return item.data;
}
2. データが null で返された場合は、データを作成して hashMap にキャッシュします
public static void cacheDataX(HttpServletRequest request, byte[] data, Integer minutes) throws ServletException
{
Item item = new Item(data);
String url = getFullURL(request);
Map<String, Item> cache = getCache(request);
log.info("Caching Item: " + url + " - Bytes: " + data.length);
synchronized (cache)
{
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, minutes);
item.expirationTime = cal.getTime();
cache.put(url, item);
}
}
複数のスレッドが say キー (この場合は url) にアクセスすると、同じキーの場所でデータがキャッシュに複数回追加されるようです [ハッシュマップが最初のスレッドのデータの書き込みを終了していないため、複数のスレッドに対して getCacheData が null を返すため]
問題を解決する方法について何か提案はありますか?