hazelcastttlhazelcast-imap

Set ttl to Imap


I have an IMap in hazelcast (key, value) with no ttl set at the time of imap.put(). Now after an event is triggered I want to set ttl to this particular key in the IMap. Since, at the time of this event I don't want to call value = imap.get(key) and then imap.put(key, value, 10, TimeUnit.SECONDS) . So how can I set ttl to that particular key ?


Solution

  • There is no straight forward way to do it other than using IMap methods. However, I would like to know the reason to avoid the following calls.

    value = imap.get(key);
    imap.put(key, value, 10, TimeUnit.SECONDS)
    

    If you want to still achieve the result, you can resort to one of the following.

    1. call imap.set(key, value, 10, TimeUnit.SECONDS), if you already have value with you. imap.set() is more efficient than imap.put() as it doesn't return the old value.

    2. If you can accommodate to use one more IMap: Use an additional map ttlMap<key, Boolean>. Whenever you need to set the ttl value for an entry in the actual imap, set an entry in ttlMap.set(key, true, 10, TimeUnit.SECONDS); . Now, add a MapListener to ttlMap using addEntryListener() method. Whenver an entry from ttlMap is evicted, entryEvicted(EntryEvent<String, String> arg0) method will get called. Evict your entry from the actual imap inside this method.

    3. If you are ready to get your hands dirty, you can modify the source in such a way that process() method of the EntryProcessor method will receive a custom Map.Entry with a new method to set ttlValue of the key.

    Hope this helps.