Scientist
Scientist

Reputation: 1464

Hazelcast TTL based iMap which updates TTL on put and get for key

There is a use case where i need to create a data structure iMap in Hazelcast where eash key has some TTL associated with it.

The TTL will be updated when there is put for that key or in short update or new key gets added. Another scenario can be for every get of that key reset the TTL also.

Thus in short for every read and write TTL gets updated.

as per Hazelcast docs there is attribute associated for seeting TTL https://docs.hazelcast.org/docs/4.2/javadoc/com/hazelcast/config/MapConfig.html#setTimeToLiveSeconds-int-

but this is for add only , how to change it for every get ?

IMAP does have API for setting the TTL https://github.com/hazelcast/hazelcast/blob/master/hazelcast/src/main/java/com/hazelcast/map/IMap.java#L3147

But not sure how to make it atomic within single get call which gets the data also and also updates the TTL.

Upvotes: 0

Views: 79

Answers (1)

Neil Stevenson
Neil Stevenson

Reputation: 3150

This variant of IMap.put() might do what you want. You can specify how long the data survives since last write and since last read.

Another alternative would be to use an EntryProcessor. Although these are normally used for amending data, it doesn't actually have to change the data. So it could take the old value and save it unchanged with a different TTL, and also return the old value to the caller.

public Object process(Entry entry) {
        Object oldValue = entry.getValue();
        ((com.hazelcast.map.ExtendedMapEntry) entry).setValue(oldValue, 30, TimeUnit.SECONDS);
        return oldValue;
    }

Upvotes: 0

Related Questions