I have a Collection in the form of a List pulled out of the database that will never change once it is pulled; every user in the system will see the same thing. I have been trying to figure out the simplest way to cache it. I know I can use CacheBuilder from Guava, but it seems like overkill to create a cached map with 1 item in it that never changes.
Asked
Active
Viewed 4,647 times
2
-
1hmm just keep that list somewhere in memory in one of your objects? – Amin J Sep 27 '16 at 18:36
-
2Guava's `Suppliers.memoize()` is preferred for single item caches. – Ben Manes Sep 27 '16 at 18:54
-
@BenManes That is exactly what I was looking for, and worked perfectly. – Kraagenskul Sep 27 '16 at 20:30
-
1Since this was written, Ben Manes has written the Caffeine Caching system. Wonder if the guava example is still the best, or using Caffeine with a constant string as the key? – Michael Rountree Mar 18 '21 at 16:53
1 Answers
4
From @BenManes above, I used Suppliers.memoize:
private Supplier<Collection<Person>> cache = Suppliers.memoizeWithExpiration(
new Supplier<Collection<Employee>>() {
public Collection<Employee> get() {
return getAllEmployees();
}
}, 1, TimeUnit.DAYS);
public Collection<Employee> getAllEmployees() {
return cache.get();
}

Kraagenskul
- 424
- 1
- 7
- 18