I have a list of objects whose maximum size is 5000. When an object has not been updated for a type specific amount of time like 5, 10 or 100 seconds, it will be deleted from the list.
What is the best or preferred option to handle such a situation?
Using a scheduled task for each object update. Cancelling old one and reset the new one.
Or using one scheduled task with fixed delay say 500 ms. Checking the old objects via time comparison...
or something else.
What do you recommend?
If you can use Google's Guava, you should give the Cache
class a try.
For example, you could have one cache for each type of object:
LoadingCache<String, ObjectOfType1> type1Cache = CacheBuilder.newBuilder()
.maximumSize(5000)
.expireAfterWrite(5, TimeUnit.SECONDS)
.removalListener(MY_LISTENER)
.build(
new CacheLoader<String, ObjectOfType1>() {
public Graph load(String key) throws AnyException {
return createExpensiveGraph(key);
}
});
And for Type2
:
LoadingCache<String, ObjectOfType2> type2Cache = CacheBuilder.newBuilder()
.maximumSize(5000)
.expireAfterWrite(10, TimeUnit.SECONDS)
.removalListener(MY_LISTENER)
.build(
new CacheLoader<String, ObjectOfType2>() {
public Graph load(String key) throws AnyException {
return createExpensiveGraph(key);
}
});
Then, you could just use a cache as if it were a Map
:
ObjectOfType1 o1 = type1Cache.get("1");
ObjectOfType2 o2 = type2Cache.get("2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With