Java Guava combination of Multimap and Cache

后端 未结 3 1151
北恋
北恋 2021-02-13 13:28

Is there any such thing as a combination of Guava\'s Cache and Multimap functionality available? Essentially, I need a collection where entries expire

3条回答
  •  孤独总比滥情好
    2021-02-13 13:45

    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 cache = CacheBuilder.newBuilder().SomeConfig.build();
    private Multimap multimap = HashMultimap.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 getFromMultimap(int id) {
       Set mapids = multimap.get(id);
       List list = new ArrayList();
       for (int i : mapids) {
          list.add(cache.getIfPresent(i));
       }
       return list;
    }
    
    
    

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

    提交回复
    热议问题