Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hazelcast cache not evicted based on <time-to-live-seconds>

We configured the <time-to-live-seconds> as 1200(20 mins) but the cache is getting evicted automatically after a minute from the cache creation time.

Can someone please tell how to make the cache live for specified time period?

like image 334
whoami Avatar asked Oct 30 '25 19:10

whoami


1 Answers

Below snippet in hazelcast.xml sets the time-to-live-seconds attribute for entries in "simpleMap" as 150 seconds. Entries that are older than 150 secs and not updated for 150 secs will get automatically evicted from the map.

<map name="simpleMap">
    <backup-count>0</backup-count>
    <max-idle-seconds>0</max-idle-seconds>
    <eviction-policy>LRU</eviction-policy>
    <time-to-live-seconds>30</time-to-live-seconds>
    <max-size>3000</max-size>
    <eviction-percentage>30</eviction-percentage>
    <merge-policy>com.hazelcast.map.merge.PutIfAbsentMapMergePolicy</merge-policy>
</map>

I have attached an entry listener (if using ver3.5, please use MapListener interface) to "simpleMap" for testing purposes, which prints the key and value whenever an entry is evicted from the map.

public static void main(String[] args) 
{
    HazelcastInstance instance = HazelcastHelper.getHazelcastInstance();
    IMap<String, String> map = instance.getMap("simpleMap");
    map.addEntryListener(new SimpleMapEntryListener(), true);

    map.put("evictme", "value");
    printTime();
    try {
        Thread.sleep(1000 * 60);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    printTime();
}

private static void printTime()
{
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    System.out.println( sdf.format(cal.getTime()) );
}

class SimpleMapEntryListener implements EntryListener<String, String>
{

    @Override
    public void entryEvicted(EntryEvent<String, String> arg0) 
    {
        System.out.println("Key : " + arg0.getKey() + " Value: " + arg0.getOldValue() + " evicted.");
        // print current time here.
    }
    // Add other overriden methods.

}

If you execute the code given above, you can see that entry <"evictme", "value"> gets evicted automatically only after 30 seconds.

You might need to check your max-idle-seconds configuration too (See that in the above example, it is set to zero which means infinite). Cache will get evicted according to max-idle-seconds, if it is set ( i.e. not zero).

like image 83
Dinesh Avatar answered Nov 03 '25 21:11

Dinesh