I\'m implementing a cache for Objects stored persistently. The idea is:
getObjectFromPersistence(long id); ///Takes about 3 seconds
You can use the Guava MapMaker for this:
ConcurrentMap graphs = new MapMaker()
.weakValues()
.makeMap();
You can even include the computation part by replacing makeMap()
with this:
.makeComputingMap(
new Function() {
public CustomObject apply(Long id) {
return getObjectFromPersistence(id);
}
});
Since what you are writing looks a lot like a cache, the newer, more specialized Cache (built via a CacheBuilder) might be even more relevant to you. It doesn't implement the Map
interface directly, but provides even more controls that you might want for a cache.
You can refer to this for a detailed how to work for CacheBuilder and here is an example for fast access:
LoadingCache cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
new CacheLoader() {
@Override
public String load(Integer id) throws Exception {
return "value";
}
}
);