Search code examples
cachingguava

Guava cache magic miss


Please help with this magic I observe here:

Map<String, RenditionMeta> map = cache.asMap();
        System.out.println("Before iterating: " + map.containsKey(objectId));
        for(String s : map.keySet()) {
            if(s.equals(objectId)) {
                System.out.println(s + " equals " + objectId + ":" + s.equals(objectId) + "-" + map.containsKey(objectId));

                System.out.println(objectId.hashCode());
                System.out.println(s.hashCode());
            }
        }

outputs:

Before iterating: false
09009e5d805f6b0b equals 09009e5d805f6b0b:true-false
1453886923
1453886923

Could someone explain how "true-false" is possible above?

cache is defined as

this.cache =  CacheBuilder.newBuilder()
                .concurrencyLevel(4)
                .weakKeys()
                .maximumSize(10000)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .build();

Solution

  • When you using weak keys option Guava cache uses identity equality for keys hence behaviour you observe. CacheBuilder#weakKeys