1

我试图在 EhCache 中找到 MemCache 的 CASMutator.cas 的等效项。本质上,我正在将 EhCache 换成 MemCache,并且需要实现一个接口,该接口调用通过 CAS 设置值。有没有人对此有任何见解?此外,鉴于我并不声称自己是这方面的专家,如果有人对 CAS 的实际工作方式/它正在做什么有任何高层次的概述,那也将不胜感激。

4

1 回答 1

3

EhCache 中等价的比较和交换方法是 net.sf.ehcache.Cache 中的 replace(Element old, Element element) 方法。此方法将“旧”元素与当前在缓存中的元素进行比较,如果匹配,则将缓存中的元素替换为“元素”。以下方法提供了一个简单的使用示例,假设“aCache”是该方法可以访问的某个 Cache 对象,并且“aCache”用于缓存 Long 类型的对象。

// Replace the cached value associated with key with newValue and
// return the original value
public Long replace(String key, Long newValue, long maxTries)
    boolean success = false;
    Long originalValue;
    Element originalElement;
    Element newElement = new Element(key, newValue);

    for (int ii = 0; !success && ii < maxTries; ++ii) {
       // Get a copy of the original List           
       originalValue = (Long) aCache.get(key).getValue();

       // Make a duplicate of the Element that exists for "key"
       originalElement = new Element(key, originalValue);

       // if the value for inKey has not changed since setting originalValue,
       // replace the value for "key" with "newValue"
       if (aCache.replace(originalElement, newElement)) {
          success = true;
       }
    }

    if (!success) {
       originalValue = null;  
    }

    return originalValue;
}

请注意,这仅在密钥已存在于缓存中时才有效。如果不是,则对 aCache.replace 的调用将返回 false 并且不会将 newElement 放入缓存中。如果你深入研究 EhCache 的内部(net.sf.ehcache.store.compound包中Segment类的replace方法),你会发现 replace 实际上是通过获取写锁来实现的。也就是说,可以假定获取写锁与使用替换方法没有什么不同。因此,理论上您可以通过调用 aCache.aquireWriteLockOnKey 来替换整个函数,执行所需的操作,然后释放写锁。

可以在 Wikipedia 上找到有关比较和交换的概述:http ://en.wikipedia.org/wiki/Compare-and-swap 。

于 2011-02-22T00:09:35.790 回答