java在CacheLoader::load调用期间更新Guava缓存中不相关的值是否安全?
我想存储{organizationId, userId} -> userEmail
的缓存,但可用的API返回给定组织的所有电子邮件。只要我得到了所有这些值,在调用CacheLoader::load
期间存储它们是否安全
private final LoadingCache<Pair<UUID, UUID>, String> emailCache = CacheBuilder
.newBuilder()
.maximumSize(10000)
.build(new CacheLoader<Pair<UUID, UUID>, String>() {
@Override
public String load(final Pair<UUID, UUID> key) throws Exception {
final UUID orgId = key.getValue0();
final List<User> users = remoteService.getAllUsers(orgId);
final Map<Pair<UUID, UUID>, String> updates = new HashMap<>();
for (User user : users) {
updates.put(Pair.with(orgId, user.getId()), user.getEmail());
}
// is this safe?
emailCache.putAll(updates);
return updates.get(key);
}
});
# 1 楼答案
不,不是,因为那会引起比赛。另一方面,使用CacheLoader执行此操作是安全的。loadAll,它专门记录了它可以返回一个包含比请求的更多条目的映射