Search code examples
javadictionarycollectionsguava

Guava CacheBuilder not working as expected


Hi I am new to google guava collections so I need collection which will expire some time period.So I have write following code but it is not removing data after expire time.Can anyone tell me what is the issue of code.

Cache<String, Object> cache = CacheBuilder.newBuilder()
                .expireAfterAccess(2, TimeUnit.MILLISECONDS)
                .build();
        Object object = new Object();            
        cache.put(object.getId(), object);
        System.out.println("size :" + cache.size());
        Thread.sleep(50000);
        System.out.println("After Size :" + cache.size());

I need to add objects to map and after expire time period it will remove from map.But above code after and before thread contains object in map.


Solution

  • The javadoc of expireAfterAccess states:

    Expired entries may be counted in Cache.size(), but will never be visible to read or write operations. Expired entries are cleaned up as part of the routine maintenance described in the class javadoc.

    That means that even though the entries are counted with .size(), they won't be visible on any other operation.

    These invalid entries will be removed automatically. According to the javadoc, this happens at the following situations:

    • The entry is accessed using get:
      The map sees the entry is outdated and removes it directly.
    • On occasional cache accesses:
      Sometimes accessing the .get() method will trigger the internal cleanup, the javadoc doesn't define any period for this.
    • Manual calls to Cache.cleanUp():
      This trigger the cleanup routine directly and removes all outdated entries.

    More information seems to be explained in the Github Wiki of the cache class.

    If you want to be notices when an entry is removed, you can use a RemovalListener. You can set this listener on the cachebuilder using .removalListener(...).