2016-06-10 20 views
0

也許我完全誤導了cache2k的工作原理。我想緩存非常昂貴的操作結果,但即使使用相同的密鑰,結果也會一直生成。首先,我想,這些鍵並不是真的相等,但即使使用equals()返回true,緩存似乎也認爲我需要新的結果。等於鍵觸發緩存加載超出預期

import org.cache2k.Cache; 
import org.cache2k.CacheBuilder; 
import org.cache2k.integration.CacheLoader; 
import org.junit.Test; 

import java.util.Date; 
import java.util.concurrent.TimeUnit; 

import static org.junit.Assert.assertEquals; 
import static org.junit.Assert.assertTrue; 

public class MyCacheTest { 

    private static int count = 0; 

    Cache<MyCacheTest.MyKey, Integer> cache = (Cache) CacheBuilder.newCache(MyCacheTest.MyKey.class, 
     Integer.class) 
     .expiryDuration(1, TimeUnit.HOURS) 
     .loader(new CacheLoader<MyCacheTest.MyKey, Integer>() { 
     @Override 
     public Integer load(MyCacheTest.MyKey p) throws Exception { 
      return costlyOperation(p); 
     } 
     }) 
     .build(); 

    private Integer costlyOperation(MyKey p) { 
    count ++; 
    return 1; 
    } 

    public class MyKey { 

    Date date; 

    @Override 
    public boolean equals(Object o) { 
     return true; 
    } 
    } 

    // OK 
    @Test 
    public void testEquals() { 
    assertTrue(new MyKey().equals(new MyKey())); 
    } 

    // FAIL, somehow calls costlyOperation twice 
    @Test 
    public void testCostlyOperationCalledOnlyOnce() { 
    cache.get(new MyKey()); 
    cache.get(new MyKey()); 
    assertEquals(count, 1); 
    } 
} 

這很可能是我的一個誤解,有人請解釋爲什麼如我所料,這是行不通的。

回答

2

您實施了equals而不是hashCode,並且此緩存實施使用hashCode。 添加:

@Override 
public int hashCode() { 
    return 0; 
} 

MyKey給出了預期的行爲。

(測試版本0.26-BETA)

+0

看到了,只是一個愚蠢的誤解,非常感謝 – globalworming