Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Guava combination of Multimap and Cache

Is there any such thing as a combination of Guava's Cache and Multimap functionality available? Essentially, I need a collection where entries expire after a given time such as available in Cache but I have non-unique keys and I need the entries to expire independently.

like image 516
hgus1294 Avatar asked Mar 05 '12 12:03

hgus1294


People also ask

Is Guava in memory cache?

Guava provides a very powerful memory based caching mechanism by an interface LoadingCache<K,V>. Values are automatically loaded in the cache and it provides many utility methods useful for caching needs.

What is Guava Multimap?

A Multimap is a new collection type that is found in Google's Guava library for Java. A Multimap can store more than one value against a key. Both the keys and the values are stored in a collection, and considered to be alternates for Map<K, List<V>> or Map<K, Set<V>> (standard JDK Collections Framework).

Is Guava cache Concurrent?

Guava's cache is built on top of Java 5's ConcurrentHashMap with a default concurrency level of 4. This setting is because that hash table is segmented into multiple smaller tables, so more segments allows for higher concurrency at a cost of a larger memory footprint.

Is Guava still relevant?

Not anymore. The features I used the most where nearly all in Java 8 (collections and I/o manipulation). Java 9 and above added efficient immutable collections and even better file management.


1 Answers

I think that Louis Wasserman provided the answer in one of the comments above, i.e. that there is no off-the-shelf combo of Multimap and Cache available. I have solved my problem/requirements with the solution outlined in pseudo-code below:

private Cache<Integer,Object> cache = CacheBuilder.newBuilder().SomeConfig.build();
private Multimap<Integer,Object> multimap = HashMultimap<Integer, Object>.create();
private AtomicInteger atomicid = new AtomicInteger(0);

public void putInMultimap(int id, Object obj) {
   int mapid = atomicid.addAndGet(1);
   cache.put(mapid,obj);
   multimap.put(id,mapid);
}
public List<Object> getFromMultimap(int id) {
   Set<Integer> mapids = multimap.get(id);
   List<Object> list = new ArrayList<Object>();
   for (int i : mapids) {
      list.add(cache.getIfPresent(i));
   }
   return list;
}

This simple 'solution' has some limitations but it works OK for me.

like image 86
hgus1294 Avatar answered Oct 13 '22 13:10

hgus1294