[英]Is it safe to update unrelated values in a Guava cache during a CacheLoader::load call?
I want to store a cache of {organizationId, userId} -> userEmail
, but the API available to me returns all emails for a given organization. 我想存储
{organizationId, userId} -> userEmail
,但是我可以使用的API返回给定组织的所有电子邮件。 So long as I'm getting all of these values, is it safe to store them all during a call to CacheLoader::load
? 只要获得所有这些值,在调用
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);
}
});
No, it isn't, as that can cause races. 不,不是,因为那会引起比赛。 On the other hand, it is safe to do this with CacheLoader.loadAll, which specifically documents that it can return a map with more entries than were requested.
另一方面,使用CacheLoader.loadAll可以安全地执行此操作,该文件专门记录了它可以返回映射的条目比所请求的更多的映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.