HashMap with weak values

前端 未结 7 2258
悲&欢浪女
悲&欢浪女 2021-02-18 14:03

I\'m implementing a cache for Objects stored persistently. The idea is:

  • Method getObjectFromPersistence(long id); ///Takes about 3 seconds
  • M
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-18 14:17

    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";
               }
           }
       ); 
    

提交回复
热议问题