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.
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:
.get()
method will trigger the internal cleanup, the javadoc doesn't define any period for this.Cache.cleanUp()
: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(...)
.