Using Java's ReferenceQueue

前端 未结 4 1599
轮回少年
轮回少年 2020-12-01 00:23

Do SoftReference and WeakReference really only help when created as instance variables? Is there any benefit to using them in method scope?

4条回答
  •  借酒劲吻你
    2020-12-01 00:58

    One common thing to do is to create maps of soft references.

    Map> cache = new HashMap<>();
    Set thingsIAmCurrentlyGetting = new HashSet();
    Object mutex = new Object();
    
    BigThing getThing(String key) {
      synchronized(mutex) {
        while(thingsIAmCurrentlyGetting.contains(key)) {
          mutex.wait();
        }
        SoftReference ref = cache.get(key);
        BigThing bigThing = ref == null ? null : ref.get();
        if(bigThing != null) return bigThing;
        thingsIAmCurrentlyGetting.add(key);
      }
    
      BigThing bigThing = getBigThing(key); // this may take a while to run.
    
      synchronized(mutex) {
        cache.put(key, bigThing);
        thingsIAmCurrentlyGetting.remove(key);
        mutex.notifyAll();
      }
    
      return bigThing;
    }
    

    I'm showing my old school here - the new java packages probably have much neater ways to do this.

提交回复
热议问题