我使用spymemcached客户端来实现我的缓存逻辑的示例代码。不知何故,我需要使用CAS来同时修改缓存中的某些内容。不明白spymemcached
只见主人已经显示了如何从这里使用CASMutation一个很好的例子:http://code.google.com/p/spymemcached/wiki/Examples#Using_CAS
但我对代码的这一部分一个问题:
// Not strictly necessary if you specify the storage as
// LinkedList (our initial value isn't), but I like to keep
// things functional anyway, so I'm going to copy this list
// first.
LinkedList<Item> ll = new LinkedList<Item>(current);
即使我仔细阅读评论,我仍然不明白它在这里试图做什么。如果我们只是使用“当前”而没有复制到“ll”会怎么样?潜在的问题是什么?
[更新]
我下面的示例代码和实现的方法是这样,将这项工作?
public <T> Set<T> addItemToSet(String key, int expire, final T newItem) throws Exception {
// This is how we modify a list when we find one in the cache.
CASMutation<Set<T>> mutation = new CASMutation<Set<T>>() {
// This is only invoked when a value actually exists.
public Set<T> getNewValue(Set<T> current) {
current.add(newItem);
return current;
}
};
HashSet<T> initialValue= new HashSet<T>();
initialValue.add(newItem);
CASMutator<Set<T>> mutator = new CASMutator<Set<T>>(memClient, getTranscoder());
return mutator.cas(key, initialValue, expire, mutation);
}
我主要关心它是否是线程安全的。