gpt4 book ai didi

java - HashMap 损坏/性能问题

转载 作者:行者123 更新时间:2023-12-04 06:20:42 26 4
gpt4 key购买 nike

目前我已经实现了 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,因为hashmap尚未完成为第一个线程写入数据]

关于如何解决问题的任何建议?

最佳答案

在添加之前(在同步块(synchronized block)内),在 cacheDataX 中添加项目是否存在的检查。

synchronized (cache)
{
if (cache.get(url) == null) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, minutes);
item.expirationTime = cal.getTime();
cache.put(url, item);
}
}

这将确保已经完成查找并返回 null 的多个线程不能都将相同的数据添加到缓存中。一个人会添加它,而其他线程将默默地忽略,因为缓存已经更新。

关于java - HashMap 损坏/性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6613463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com