Reputation: 105
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?
Upvotes: 5
Views: 854
Reputation: 34450
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");
Upvotes: 1
Reputation:
I'm actually using an implementation which uses a Map<Object, Long>
for storing the expiration times of each element, and a java.util.Timer
to run every n seconds, removing every expired element.
I can't really say it's the best implementation, since I only use it for a few hundred simple elements (i.e. not complex objects).
Upvotes: 0